Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 7 generics type inference: return value vs method argument

Tags:

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>) 
like image 633
gontard Avatar asked Mar 15 '13 15:03

gontard


People also ask

Does Java 7 support type inference?

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.

What is infer generic type arguments?

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.

Why should we use generics in Java?

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.

Why are parameterized types important?

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.


1 Answers

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).

like image 110
Joachim Sauer Avatar answered Oct 11 '22 12:10

Joachim Sauer