In Java it is tiring to have to write:
Pair<String, String> pair = new Pair<String, String>("one", "two");
It would be nice if the types were inferred for you so you could at least do this:
Pair<String, String> pair = new Pair("one", "two");
And skip the generic params again.
You can make a static method that can cheat around it like so:
public static <T, S> Pair<T, S> new_(T one, S two) {
return new Pair<T, S>(one, two);
}
And then use it like: Pair.new_("one", "two")
.
Is it possible to build the type inferencing into the constructor so that hack can be avoided?
I was thinking of something like:
public <S,T> Pair(S one, T two) {
this.one = one;
this.two = two;
}
But then you run into generic type collisions. Does anyone have any thoughts?
It s common to have a helper method which will imply the types for you.
Pair<String, String> pair = Pair.of("one", "two");
then it doesn't seem like such a hack.
It would also be nice if Java had a built in Pair class. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With