Adding var to lambda parameters

Java allows for the use of the reserved word var with lambda parameters, to align its syntax with the declaration of local variables, which can now use var.

Let's modify the examples from the preceding section, adding var to the lambda parameters:

(var age) -> age > 10; 
(var age) -> age > 10? "Kid" : "Not a Kid"; 
(var age) -> {System.out.println();}; 
() -> {return Math.random() + "Number";}; (var name, var list) -> { return ( list.stream() .filter(e ->
e.getName().startsWith(name)) .map(Person::getAge) .findFirst() ); };
The main reason for allowing the addition of var to lambda parameters is to align the usage with the syntax of the local parameters declared using var.

If you are using var with lambda parameters, you must use it with all of the lambda parameters. You can't mix implicitly-typed or explicitly-typed parameters with the parameters that use var. The following code example won't compile:

(var x, y) -> x + y;                         // won't compile 
(var x, Integer y) -> x + y;                 // won't compile 

You cannot enclose the parameters of a lambda expression using round brackets (()) if you are using just one method parameter. But, you can't drop () if you are using var with your lambda parameters. Here is some sample code to illustrate this further:

(int x) -> x > 10;                         // compiles 
(x) -> x > 10;                             // compiles 
x -> x > 10;                               // compiles 
(var x) -> x > 10;                         // compiles 
var x -> x > 10;                           // Won't compile 
You can't mix implicitly-typed or explicitly-typed lambda parameters with the parameters that use var.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.197.95