Java Reference
In-Depth Information
The output is shown here:
Notice that the lambda expression uses the
indexOf( )
method defined by the
String
class
to determine if one string is part of another. This works because the parameters
a
and
b
are
determined by type inference to be of type
String
. Thus, it is permissible to call a
String
method on
a
.
Ask the Expert
Q
:
Earlier you mentioned that I can explicitly declare the type of a parameter in a
lambda expression if needed. In cases in which a lambda expression requires
two or more parameters, must I specify the types of all parameters, or can I let
one or more use type inference?
A
:
In cases in which you need to explicitly declare the type of a parameter, then all of
the parameters in the list must have declared types. For example, this is legal:
But this is not legal:
Nor is this legal:
Block Lambda Expressions
The body of the lambdas shown in the preceding examples consist of a single expression.
These types of lambda bodies are referred to as
expression bodies
, and lambdas that have