Expression body: It is the simplest lambda expression body type, composed of a single expression. The code to the right of the lambda operator is a single expression that is automatically returned.
Block body: Unlike the expression body, the block body allows multiple instructions. This expands the operations that can be done with lambdas, such as variable declarations, loops, if and switch statements. To return a value, you must explicitly use a return.
statementExample of block body usage: A block lambda can be used to find the smallest positive factor of an integer, through a functional interface like NumericFunc, which takes an int and returns an int.
// A block lambda that finds the smallest positive factor
// of an int value.
interface NumericFunc {
int func(int n);
}
class BlockLambdaDemo {
public static void main(String args[])
{
// This block lambda returns the smallest positive factor of a value.
// A block lambda expression
NumericFunc smallestF = (n) -> {
int result = 1;
// Gets the absolute value of n.
n = n < 0? -n : n;
for(int i=2; i <= n/i; i )
if((n % i) == 0) {
result = i;
break;
}
return result;
};
System.out.println("Smallest factor of 12 is " smallestF.func(12));
System.out.println("Smallest factor of 11 is " smallestF.func(11));
}
}
Output:
Smallest factor of 12 is 2
Smallest factor of 11 is 1
The above is the detailed content of Block lambda expressions. For more information, please follow other related articles on the PHP Chinese website!