Java 7 generics type inference: return value vs method argument
generics, java, type-inference
Solution
This is one of the places where type inference does not yet work as expected.
Unfortunately that behaviour is perfectly valid and conforming.
The good news is that Java 8 will include improved type inference (JEP 101), so situations like this should compile just as you'd expect it:
It seems reasonable that the compiler should be able to infer the type when the result of such a generic method invocation is passed to another method [...].
Unfortunately, this is not allowed in JDK 5/6/7 – the only option available to the programmer is to use an explicit type-argument.
Apart from the direct improvements (i.e. situations like the ones you mention here), this change is also necessary for being able to use Lambdas (JEP 126) more efficiently (i.e. without having to type a lot of type information).
Problem
Why the compiler is able to correctly infer the `String` type parameter in the case of a function return type. ``` public class Generics { private static List<String> function() { return new ArrayList<>(); } } ``` but it fail when the type to infer is a method parameter : ``` public class Generics { public static void main(String[] args) { method(new ArrayList<>()); } private static void method(List<String> list) { } } ``` The error in this case is : ``` The method method(List<String>) in the type Generics is not applicable for the arguments (ArrayList<Object>) ```