Type Inference in Java

Type Inference in Java is a Java Compiler’s ability base on the declaration, the calling to determine the datatype, without explicitly declaring it, reducing redundancy code.

For you to understand more, I will take an example as follows.

Assuming you are working with the List object, we usually initialize it as follows:

As you can see, we have to declare the same data type on the left and right of the above expression. Why do we have to repeat it twice? Why not declare once and the rest to let Java Compiler self-understand?

This is what causes Type Inference to be introduced. With Type Inference, we write the following:

You see, using Type Inference we can eliminate a “<String>”.

To apply Type Inference to the above example, you simply replace the right datatype with Diamond character (“<>”).

The second example is the Lambda Expression.

Suppose you have an interface like this:

Now, I will use this interface in my application with Lambda Expression as follows:

Result:

Type Inference in Java

Obviously, as you can see, although we do not use the return statement in the Lambda Expression, the Java Compiler, based on how we declare the interface and method in this interface, automatically understands that there will be a value returned at the end of the body in Lambda Expression.

5/5 - (1 vote)

Add Comment