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:
1 |
List<String> text = new ArrayList<String>(); |
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:
1 |
List<String> text = new ArrayList<>(); |
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:
1 2 3 4 5 6 |
package com.huongdanjava.javaexample; public interface Calculator { int add(int a, int b); } |
Now, I will use this interface in my application with Lambda Expression as follows:
1 2 3 4 5 6 7 8 9 |
package com.huongdanjava.javaexample; public class Example { public static void main(String[] args) { Calculator calculator = (a, b) -> a + b; System.out.println(calculator.add(2, 3)); } } |
Result:
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.