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>)
Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context.
Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned.
Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
Types defined using parameters are called parameterized types. Parameterized types perform an important role in Haskell, as they allow you to define generic data structures that work with a wide range of existing data.
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).
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