Java Reference
In-Depth Information
Declaring No Parameters
If a lambda expression does not take any parameters, you need to use empty parentheses.
// Takes no parameters
() -> { System.out.println("Hello"); }
It is not allowed to omit the parentheses when the lambda expression takes no parameter. The following
declaration will not compile:
-> { System.out.println("Hello"); }
Parameters with Modifiers
You can use modifiers, such as final , in the parameter declaration for explicit lambda expressions. The following two
lambda expressions are valid:
(final int x, final int y) -> { return x + y; }
(int x, final int y) -> { return x + y; }
The following lambda expression will not compile because it uses the final modifier in parameter declarations,
but omits the parameter type:
(final x, final y) -> { return x + y; }
Declaring Body of Lambda Expressions
The body of a lambda expression can be a block statement or a single expression. A block statement is enclosed in
braces; a single expression is not enclosed in braces.
When a block statement is executed the same way as a method's body. A return statement or the end of the body
returns the control to the caller of the lambda expression.
When an expression is used as the body, it is evaluated and returned to the caller. If the expression evaluates to
void , nothing is returned to the caller. The following two lambda expressions are the same; one uses a block statement
and the other an expression:
// Uses a block statement. Takes two int parameters and returns their sum.
(int x, int y) -> { return x + y; }
// Uses an expression. Takes a two int parameters and returns their sum.
(int x, int y) -> x + y
The following two lambda expressions are the same; one uses a block statement as the body and the other an
expression that evaluates to void :
// Uses a block statement
(String msg) -> { System.out.println(msg); }
// Uses an expression
(String msg) -> System.out.println(msg)
 
Search WWH ::




Custom Search