A lambda expression represents an instance of a functional interface.
One lambda expression may map to different functional interface types depending on the context.
The compiler infers the type of a lambda expression.
In the following code there are two functional interfaces, Processor
and SecondProcessor
.
Processor
has a method named getStringLength
which accepts
a string as parameter and returns and int
.
SecondProcessor
has a method named noName
which also
accepts a string as parameter and returns an int
.
From the code we can see that we can assign two identical lambda expressions to them.
public class Main { public static void main(String[] argv) { Processor stringProcessor = (String str) -> str.length(); SecondProcessor secondProcessor = (String str) -> str.length(); //from w w w. ja va 2s . c o m //stringProcessor = secondProcessor; //compile error String name = "Java Lambda"; int length = stringProcessor.getStringLength(name); System.out.println(length); } } @FunctionalInterface interface Processor { int getStringLength(String str); } @FunctionalInterface interface SecondProcessor { int noName(String str); }
The code above generates the following result.
Processor
or SecondProcessor
is called target type.
The process of inferring the type of a lambda expression is called target typing.
The compiler uses the following rules to determine whether a lambda expression is assignable to its target type: