Saturday, January 5, 2019

Java 8 - Type Inference

Java 8 – Type Inference

Type inference was first introduced in JDK 7 and later improved in JDK 8. It is a feature of Java which provides ability to compiler to look at each method invocation and corresponding declaration to determine the type of argument(s).

The inference algorithm checks the types of the arguments and,if available, assigned type is returned. It tries to find a specific type which can full fill all type parameters.

Till Java 6, We have to declare an Arraylist by mentioning its type explicitly at both side.
            List<Integer> numbers = new ArrayList<Integer>();
and if we keep the type as blank at right side then Compiler generates unchecked conversion.
            List<Integer> numbers = new ArrayList<>();

With JDK 7, It got improved and we started mentioning the type of arraylist only at one side. Below we can left second side as blank diamond and compiler will infer type of it by type of reference variable. Now, compiler will not generate any warning
            List<Integer> numbers = new ArrayList<>();

Improved Type Inference in JDK 8
Now, we can call specialized method without explicitly mentioning of type of arguments.
            sum(new ArrayList<>());

Let’s see the java implementation

No comments:

Post a Comment