Java Reference
In-Depth Information
interface ActionCode{
int returnCode(String codestr);
}
The code implies that the lambda expression implements the
returnCode
meth-
od, which is defined within the
ActionCode
interface. This method accepts a string
argument (
codestr
), which is passed to the lambda expression, returning an
int
.
Therefore, from this example you can see that a lambda can encapsulate the functional-
ity of a method body.
Note
A lambda expression can contain any statement that an ordinary Java method
contains. However, the
continue
and
break
keywords are illegal at the top level.
6-2. Enabling the Use of Lambda Expres-
sions
Problem
You are interested in authoring code that enables the use of lambda expressions.
Solution 1
Write custom functional interfaces that can be implemented via lambda expressions.
All lambda expressions implement a functional interface, a.k.a. an interface with one
abstract method definition. The following lines of code demonstrate a functional inter-
face that contains one method definition.
interface ReverseType {
String reverse(String text);
}
The functional interface contains a single abstract method definition, identified as
String reverse(String text)
. The following code, which contains a lambda
expression, demonstrates how to implement
ReverseType
.