Java Reference
In-Depth Information
method is called through the target, the lambda expression is executed. Thus, a lambda ex-
pression gives us a way to transform a code segment into an object.
In the preceding example, the lambda expression becomes the implementation for the
getValue( )
method. As a result, the following displays the value 98.6:
Because the lambda expression assigned to
myVal
returns the value 98.6, that is the value
obtained when
getValue( )
is called.
If the lambda expression takes one or more parameters, then the abstract method in the
functional interface must also take the same number of parameters. For example, here is a
functional interface called
MyParamValue
, which lets you pass a value to
getValue( )
:
You can use this interface to implement the reciprocal lambda shown in the previous sec-
tion. For example:
You can then use
myPval
like this:
Here,
getValue( )
is implemented by the lambda expression referred to by
myPval
, which
returns the reciprocal of the argument. In this case, 4.0 is passed to
getValue( )
, which re-
turns 0.25.
There is something else of interest in the preceding example. Notice that the type of
n
is
not specified. Rather, its type is inferred from the context. In this case, its type is inferred
from the parameter type of
getValue( )
as defined by the
MyParamValue
interface, which
is
double
. It is also possible to explicitly specify the type of a parameter in a lambda ex-
pression. For example, this is also a valid way to write the preceding: