Suppose I have a simple method like this for processing two lists:
public static <B> void foo(List<B> list1, List<B> list2) {
}
And suppose I want to call it like this:
foo(ImmutableList.of(), ImmutableList.of(1));
This won't compile, because javac
isn't smart enough to figure out I was trying to create two lists of Integers. Instead, I have to write:
foo(ImmutableList.<Integer>of(), ImmutableList.of(1));
How should I change the declaration of foo
to allow the first version to work as well as the second one?
I'm pretty sure Java's type inference isn't powerful enough to handle unification.
What you could do is return an intermediate object of some sort, and change the call site to be something like:
foo(list1).and(list2)
But then it would still only be able to infer from left to right, so you'd have to call it as:
foo(ImmutableList.of(1)).and(ImmutableList.of());
The only setting in which I forsee this being an inconvenience for you is when you do this a lot. In that case you can make a
private static final ImmutableList<Integer> EMPTYINTLIST = ImmutableList.<Integer>of();
and use your EMPTYINTLIST
in your calls.
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