Explicit and implicit lambda expression
Description
A lambda expression which does not declare the its parameters' type is called implicit lambda expression.
An explicit lambda expression is a lambda expression which declares its parameters' type.
The compiler will infer the types of parameters for implicit lambda expression.
Example
The following code
creates interface with single method and uses it as lambda expression type.
When creating the lambda expression we declare the type of the parameter s1
to
have the Integer
type.
public class Main {
// ww w .j a v a 2 s.c o m
public static void main(String[] args) {
MyIntegerCalculator myIntegerCalculator = (Integer s1) -> s1 * 2;
System.out.println("1- Result x2 : " + myIntegerCalculator.calcIt(5));
}
}
interface MyIntegerCalculator {
public Integer calcIt(Integer s1);
}
The code above generates the following result.
Example 2
Here is the demo again without using the type. When ignoring the type the compiler has to figure it out.
public class Main {
/*from ww w.j ava2s . c om*/
public static void main(String[] args) {
MyIntegerCalculator myIntegerCalculator = (s1) -> s1 * 2;
System.out.println("1- Result x2 : " + myIntegerCalculator.calcIt(5));
}
}
interface MyIntegerCalculator {
public Integer calcIt(Integer s1);
}
The code above generates the following result.