How does the java return tuple work?

430    Asked by Amitraj in Java , Asked on Oct 10, 2022

Sometimes you want to return multiple values from a function. How is this normally done in Java? One option is to use an array, like this Python snippet that returns a list or tuple:

value, success = read_unreliably()
if success:
    print value
Another option would be to return a hash/dict, like this JavaScript example:
var result = readUnreliably()
if (result.success) {
    alert(value);
}

One more would be to create a custom object just for this purpose, like this Java example:

ReadUnreliablyResult result = readUnreliably()
if (result.getSuccess()) {
    System.out.println(result.getValue());
}

Of course you can also just use some global variables to store what you need instead of passing things around, but let's just say that's not an option.

Answered by Alan Taylor

Yes, , the way to create a struct / java return tupple / record in Java is by creating a class. If it's only for internal use, I prefer to use a small immutable struct-like class with public fields.


Examples:

public class Unreliably {
    public final boolean success;
    public final int value;
    public Unreliably(boolean success, int value) {
        this.success = success; this.value = value;
    }
}

This is much easier to do in Scala: case class Unreliably(success: Boolean, value: Int)



Your Answer

Interviews

Parent Categories