Java Reference
In-Depth Information
As mentioned, the lambda expression must be compatible with the abstract method that
it is intended to implement. For this reason, the commented-out lines at the end of the
preceding program are illegal. The first, because a value of type
String
is not compat-
ible with
double
, which is the return type required by
getValue( )
. The second, because
getValue(int)
in
MyParamValue
requires a parameter, and one is not provided.
A key aspect of a functional interface is that it can be used with any lambda expression
that is compatible with it. For example, consider the following program. It defines a func-
tional interface called
NumericTest
that declares the abstract method
test( )
. This method
has two
int
parameters and returns a
boolean
result. Its purpose is to determine if the two
arguments passed to
test( )
satisfy some condition. It returns the result of the test. In
main(
)
, three different tests are created through the use of lambda expressions. One tests if the
first argument can be evenly divided by the second; the second determines if the first ar-
gument is less than the second; and the third returns
true
if the absolute values of the ar-
guments are equal. Notice that the lambda expressions that implement these tests have two
parameters and return a
boolean
result. This is, of course, necessary since
test( )
has two
parameters and returns a
boolean
result.