Saturday, April 7, 2012

Type inference based on return type

Consider a simple method in java:

private<E> List<E> newArrayList(){
     return new ArrayList<E>();

and a test for this method:
List<Integer> anIntegerList = newArrayList();
 List<String> aStringList = newArrayList();

This works without any errors and the type returned by the method is correctly inferred to be an Integer and String resepectively! the reason is - compiler normally infers the type based on the arguments of the method, in this specific case there are no arguments and so the compiler infers the type based on the left hand side of the assignment.

If I really want to force a specific type, then explicitly the type can be specified when calling the method:

List<Double> aDoubleList = this.<Double>newArrayList();

Gauva libraries make use of this inference technique to provide concise static constructors for the collection classes.

No comments:

Post a Comment