Java Reference
In-Depth Information
One of the goals of the lambda expression was to keep its syntax concise and let the compiler infer the details.
The following sections discuss the shorthand syntax for declaring lambda expressions.
Omitting Parameter Types
You can omit the declared type of the parameters. The compiler will infer the types of parameters from the context in
which the lambda expression is used.
// Types of parameters are declared
(int x, int y) -> { return x + y; }
// Types of parameters are omitted
(x, y) -> { return x + y; }
If you omit the types of parameters, you must omit it for all parameters or for none. You cannot omit for some and
not for others. The following lambda expression will not compile because it declares the type of one parameter and
omits for the other:
// A compile-time error
(int x, y) -> { return x + y; }
a lambda expression that does not declare the types of its parameters is known as an implicit lambda expression
or an implicitly-typed lambda expression. a lambda expression that declares the types of its parameters is known as an
explicit lambda expression or an explicitly-typed lambda expression.
Tip
Declaring a Single Parameter
Sometimes a lambda expression takes only one parameter. You can omit the parameter type for a single parameter
lambda expression as you can do for a lambda expression with multiple parameters. You can also omit the
parentheses if you omit the parameter type in a single parameter lambda expression. The following are three ways to
declare a lambda expression with a single parameter:
// Declares the parameter type
(String msg) -> { System.out.println(msg); }
// Omits the parameter type
(msg) -> { System.out.println(msg); }
// Omits the parameter type and parentheses
msg -> { System.out.println(msg); }
The parentheses can be omitted only if the single parameter also omits its type. The following lambda expression
will not compile:
// Omits parentheses, but not the parameter type, which is not allowed.
String msg -> { System.out.println(msg); }
 
 
Search WWH ::




Custom Search