Java Reference
In-Depth Information
Here is an example of a functional interface:
In this case, the method getValue( ) is implicitly abstract, and it is the only method defined
by MyValue . Thus, MyValue is a functional interface, and its function is defined by
getValue( ) .
As mentioned earlier, a lambda expression is not executed on its own. Rather, it forms
the implementation of the abstract method defined by the functional interface that specifies
its target type. As a result, a lambda expression can be specified only in a context in which
a target type is defined. One of these contexts is created when a lambda expression is as-
signed to a functional interface reference. Other target type contexts include variable ini-
tialization, return statements, and method arguments, to name a few.
Let's work through a simple example. First, a reference to the functional interface
MyValue is declared:
Next, a lambda expression is assigned to that interface reference:
This lambda expression is compatible with getValue( ) because, like getValue( ) , it has no
parameters and returns a double result. In general, the type of the abstract method defined
by the functional interface and the type of the lambda expression must be compatible. If
they aren't, a compile-time error will result.
As you can probably guess, the two steps just shown can be combined into a single state-
ment, if desired:
Here, myVal is initialized with the lambda expression.
When a lambda expression occurs in a target type context, an instance of a class is auto-
matically created that implements the functional interface, with the lambda expression de-
fining the behavior of the abstract method declared by the functional interface. When that
Search WWH ::




Custom Search