Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java not support type inference for constructors?

Tags:

java

generics

E.G. to create an ArrayList of Strings we have to do something like

List<String> list = new ArrayList<String>();

whereas it should be able to infer the parameter type for the constructor so that we only have to type

List<String> list = new ArrayList();

Why can't the type be infered in the same way that type parameters are infered for generic methods.

like image 987
Tarski Avatar asked Sep 03 '09 14:09

Tarski


People also ask

Why does Java not have type inference?

So, I can imagine that type inference was probably not supported because Java was aimed at programmers coming from C++, Pascal, or other mainstream languages that did not have it (principle of least surprise).

Does Java support type inference?

Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable.

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.

How does type inference work in Java?

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.


1 Answers

This is a Java 7 improvement also known as the diamond operator. The syntax will be:

List<String> strings = new ArrayList<>();

The official proposal, accepted for inclusion in Project Coin is Improved Type Inference for Generic Instance Creation

According to Rémi Forax, the change is already in the mercurial repository.

like image 199
Robert Munteanu Avatar answered Sep 18 '22 23:09

Robert Munteanu