jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 12:33pm on 19/01/2021
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.

Reply

This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Links

March

SunMonTueWedThuFriSat
  1
 
2
 
3
 
4
 
5
 
6
 
7
 
8
 
9
 
10
 
11
 
12
 
13
 
14
 
15 16
 
17
 
18
 
19
 
20
 
21
 
22
 
23
 
24
 
25
 
26
 
27
 
28
 
29
 
30
 
31