jbanana: Badly drawn banana (Default)
J Banana ([personal profile] jbanana) wrote in [community profile] java_dev2021-01-19 12:33 pm

Multiple returns

In some languages you can write a method that returns two things, and then say something like
a, b = getCatAndDog()
That's not allowed in Java. Why not? You could do something like...
class Pair<T,U>{/*boilerplate to handle two things*/}

Pair<Cat,Dog> x = getCatAndDog();
Cat a = x.getLeft();
Dog b = x.getRight();
Ouch, and what if you want more than two?

I have done it with Object[] but that's pretty hacky, and I've seen people return a map of names to values, but both of those are type unsafe (you'd have to cast the return values).

There's a syntax for multiple declarations...
int a, b;
... so that could be extended to allow multiple types:
Cat, Dog a, b = getCatDog();
or with the new type inference:
var a, b = getCatAndDog();
Now I'm wondering how to make that proposal...

Edit: The process seems to be to sign up at jcp.org and submit a JSR. Bit daunting.