Java Reference
In-Depth Information
expression bodies are sometimes called expression lambdas . In an expression body, the
code on the right side of the lambda operator must consist of a single expression, which
becomes the lambda's value. Although expression lambdas are quite useful, sometimes the
situation will require more than a single expression. To handle such cases, Java supports a
second type of lambda expression in which the code on the right side of the lambda operat-
or consists of a block of code that can contain more than one statement. This type of lambda
body is called a block body . Lambdas that have block bodies are sometimes referred to as
block lambdas .
A block lambda expands the types of operations that can be handled within a lambda
expression because it allows the body of the lambda to contain multiple statements. For ex-
ample, in a block lambda you can declare variables, use loops, specify if and switch state-
ments, create nested blocks, and so on. A block lambda is easy to create. Simply enclose
the body within braces as you would any other block of statements.
Aside from allowing multiple statements, block lambdas are used much like the expres-
sion lambdas just discussed. One key difference, however, is that you must explicitly use
a return statement to return a value. This is necessary because a block lambda body does
not represent a single expression.
Here is an example that uses a block lambda to find the smallest positive factor of an
int value. It uses an interface called NumericFunc that has a method called func( ) , which
takes one int argument and returns an int result. Thus, NumericFunc supports a numeric
function on values of type int .
Search WWH ::




Custom Search