Unlike Python, Java doesn't natively support tuples. Therefore, is doesn't provide such a useful possibility as tuple assignment.
How would you implement it? Your solution should:
- Be as universal as possible.
- Be as readable as possible.
- Contain no temporary variables at the place of assignment.
- Utility methods are allowed, but only static ones. No Tuple classes should be created or imported. No arrays or collections should be used.
I'll give a simple example. Don't pay much attention to contents of the *Func()
methods. They may be inlined or depend on less variables or on other variables additionally.
public class TupleAssignment {
static String sFunc(String s, int i, double d) {
return i + s + d;
}
static int iFunc(String s, int i, double d) {
return i + s.length() - (int) d;
}
static double dFunc(String s, int i, double d) {
return (double) i / s.length() + d;
}
public static void main(String[] args) {
String s = "ABCDE";
int i = 2;
double d = 0.6;
String s1 = sFunc(s, i, d);
int i1 = iFunc(s, i, d);
double d1 = dFunc(s, i, d);
s = s1;
i = i1;
d = d1;
System.out.println(s + ", " + i + ", " + d);
}
}
This produces the right result:
2ABCDE0.6, 7, 1.0
but requires additional variables s1
, i1
, d1
. If you try to get rid of them this way:
s = sFunc(s, i, d);
i = iFunc(s, i, d);
d = dFunc(s, i, d);
you'll get the wrong result:
2ABCDE0.6, 11, 1.8222222222222224
How to get previous result complying with the above four requirements? If you see a nice partial solution, add it as an answer too.
Note that this question is not about making Tuples. You don't need to implement tuple return values. You don't even need to know what a tuple is. It is about multiple-assignment (call this simultaneous assignment or vector-assignment, if you prefer).