Java generics: inferring types from two parameters
•
Java
Suppose I have a simple way to handle two lists:
public static <B> void foo(List<B> list1,List<B> list2) { }
Suppose I want to call it this:
foo(ImmutableList.of(),ImmutableList.of(1));
This will not compile because javac is not smart enough to figure out that I am trying to create two integer lists Instead, I must write:
foo(ImmutableList.<Integer>of(),ImmutableList.of(1));
How should I change the foo declaration to allow the first and second versions to work together?
Solution
I'm pretty sure Java's type inference is not enough to handle unification
What you can do is return some intermediate object and change the calling site to:
foo(list1).and(list2)
But it can only be inferred from left to right, so you must call it:
foo(ImmutableList.of(1)).and(ImmutableList.of());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码