Generalized target type inference – java 8

/, Java 8/Generalized target type inference – java 8

What is type inference ?

Invoking a generic method or constructor without specifying a type between angle brackets is called type inference. Type inference is a Java compiler’s ability to look at each method invocation and corresponding declaration to determine the type argument that make the invocation applicable.

To understand type inference in java 8 more clearly let’s see history of generics.

Generics in Java :

To provide type safety and to resolve typecasting issues the generics was introduced in Java 5, that introduced type parameters for classes and methods.

For example to create Araylist in java 5 the following approach is used. Here Integer is type parameter that should specify both sides.

In java 7 this was improved as below. The diamond operator <> introduced. The compiler can infer parameter types for constructors of generic classes. Here compiler has ability infer parameter type without providing type parameter in angle brackets. This is called type inference.

But the compiler could not figure out the generic types for a method invocation. see below example.

Type inference Java 7 example :

Above example if you compile against java 1.7 the below line give the compilation error. Compiler could not figure out the generic types for a method invocation in java 7.

Type inference Java 8 example :

Java 8 added support generalized target type inference in method context, so we can now remove the specific generic parameter type in method invocations. See below example, run this example in java 1.8, you wont get any compiler error.

One Comment

  1. onesies animals June 28, 2018 at 12:45 am - Reply

    onesies animals

    ost but I was wondering if you could write a litte more on this subject? I’d be very grateful if you could elaborate a little bit more. Thank you!

Leave a Reply

%d bloggers like this: