views:

442

answers:

4

I have a Java method which returns an array of doubles. I would then like to store these values in individual variables in the calling function. Is there an elegant way of doing this in Java.

I could write it as this:

double[] returnValues = calculateSomeDoubles();
double firstVar  = returnValues[0];
double secondVar = returnValues[1];

I was just wondering if there was some way of compressing this down to a single line? Something like:

(firstVar, secondVar) = calculateSomeDoubles();

This type of thing is quite easy when scripting, but the stronger typing of Java means it probably isn't possible.

+1  A: 

The only way would be using reflection, granted you know upfront how many items method "calculateSomeDouble" will return.

A variation of this would be needed. But as you see there's more to code.

So the question that raises is? DO you want this for an automated stuff ? Or to save time for developing ( avoid having to copy/paste ) ?

If you want to automate some task ( like filling an object at runtime ) then it is worth to do the reflection call and write the method.

You will need to set the value rather than only print it.

The client call should look like

 SomeUtility.fill( myObject , withDoublesFromMethod() );
OscarRyz
+5  A: 

Basically no, this isn't possible.

You'll have to return an object that contains the values.

MyObject myObject = calculateMyObject();
Nick Holt
+1  A: 

When you no that you get 2 double values back you can call your methode usig call by reference

void methode(double[] array)

You can submit a array with length 2 and put the values iside the methode.

Or you return a Collection if the returned values can change.

List methode()

Ia m not the friend of returning values like

double[] methode()

When you use Lists or Collections the methode is ot as static as you handle with arrays. You can better reuse the methode in other projects.

Markus Lausberg
A: 

My first instinct is to question your motivation for doing something like this. If you have a group of related doubles in your program, why aren't you storing them in a List?

If you were you could do something like this:

List<Double> myVars = Arrays.asList(calculateSomeDoubles());

But if you must store them in individual variables it cannot be done cleanly in one line. I advise you not to use some of the reflection based solutions being suggested. It would likely be much better to simply write out your assignments in multiple lines as you first suggested.

Justin Standard
I considered using a list as a return value (or something similar, maybe a HashMap), but I figured that for readability I would end up assigning them to better names anyway, so it is easier to return an array of doubles.
kaybenleroll