Is there an elegant way to do the following: let int[] makeArray() be a method that returns a length 2 integer array. Then
int[] t = makeArray(); int ta = t[0]; tb = t[1];
Nicer would be
int[] {ta,tb} = makeArray();
Is there an elegant way to do the following: let int[] makeArray() be a method that returns a length 2 integer array. Then
int[] t = makeArray(); int ta = t[0]; tb = t[1];
Nicer would be
int[] {ta,tb} = makeArray();
There isn't unless makeArray()
returns the same array after each call (which I'm assuming it doesn't due to its name). If this is the case, however, you could write:
int ta = makeArray()[0];
int tb = makeArray()[1];
Otherwise, the value returned from makeArray()
would need to be cached so that it can be used to set the variables that follow it.
What you're describing is returning multiple values, which would be nice but isn't supported in java, you have to wrap them in an object.
However depending on your use case you could refactor into something elegant using lambdas, e.g. the following where I've rearranged so the makeArray
becomes withDataArray
and you pass it a lambda to process the array data. You could make it have a return easily enough as well. Change BiConsumer
to BiFunction
and have withDataArray return the result of the BiFunction
public static void main(String[] args){
withDataArray( (a,b) -> {
System.out.println(a+b);
});
}
public static void withDataArray(BiConsumer<Integer, Integer> applier){
applier.accept(1,2);
}