Java Reference
In-Depth Information
This syntax was chosen by the Java language designers because it was well received in other
languages such as C# and Scala, which have a similar feature. The basic syntax of a lambda is
either
(parameters) -> expression
or (note the curly braces for statements)
(parameters) -> { statements; }
As you can see, lambda expressions follow a simple syntax. Working through Quiz 3.1 should let
you know if you understand the pattern.
Quiz 3.1: Lambda syntax
Based on the syntax rules just shown, which of the following are not valid lambda expressions?
1 . () -> {}
2 . () -> "Raoul"
3 . () -> {return "Mario";}
4 . (Integer i) -> return "Alan" + i;
5 . (String s) -> {"Iron Man";}
Answer:
Only 4 and 5 are invalid lambdas.
1 . This lambda has no parameters and returns void. It's similar to a method with an empty body:
public void run() { }.
2 . This lambda has no parameters and returns a String as an expression.
3 . This lambda has no parameters and returns a String (using an explicit return statement).
4 . return is a control-flow statement. To make this lambda valid, curly braces are required as
follows: (Integer i) -> {return "Alan" + i;}.
Search WWH ::




Custom Search