1

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();
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
ron shenk
  • 27
  • 2
  • Are you trying to create an array based off of the values of `ta` and `tb` or are you trying to resolve the values in the array to `ta` and `tb`? – GBlodgett Jun 10 '18 at 15:27

2 Answers2

0

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.

Kröw
  • 504
  • 2
  • 13
  • 31
-1

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);
}
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77