Last week we looked at local variable type inference. This week we’ll stay on the same theme and look at local variable syntax for lambda parameters. This Java enhancement was delivered in JDK 11.
If lambdas are still giving you a headache, read the quick introduction to lambdas in Java.
Local variable syntax for lambda parameters allows us to use the var
reserved type name when declaring the formal parameters of implicitly typed lambda expressions.
Explicit vs. Implicit Parameters
Remember that we can either explicitly or implicitly assign types to formal parameters in lambdas expressions.
Here is an example of an explicitly typed formal parameter:
Comparator<String> comp1 = (String first, String second) -> first.length() - second.length();
We can omit the formal parameter types if the compiler can infer the correct types from the declaration:
Comparator<String> comp2 = (first, second) -> first.length() - second.length();
Using the var Reserved Type Name
For consistency with using var
for local variable type inference, we can now use var
for the formal parameters of an implicitly typed lambda expression:
Comparator<String> comp3 = (var first, var second) -> second.length() - first.length();
It’s a personal choice as to whether we want to use var
in this situation because the type inferred for the implicitly typed parameter (i.e. without var
) is the same as the type inferred using var
.
Restrictions on Local Variables in Lambda Parameters
An implicitly typed lambda expression must use var
for all its formal parameters or for none of them. We cannot use explicit data types for some formal parameters and use var
for others.
// all correct Comparator comp4 = (first, second) -> first.hashCode() - second.hashCode(); Comparator comp5 = (Integer first, Integer second) -> first.hashCode() - second.hashCode(); Comparator comp6 = (var first, var second) -> first.hashCode() - second.hashCode(); Comparator<Integer> comp7 = (first, second) -> first.hashCode() - second.hashCode(); Comparator<Integer> comp8 = (Integer first, Integer second) -> first.hashCode() - second.hashCode(); Comparator<Integer> comp9 = (var first, var second) -> first.hashCode() - second.hashCode(); // all incorrect Comparator<Integer> comp10 = (Integer first, var second) -> first.hashCode() - second.hashCode(); Comparator<Integer> comp11 = (var first, Integer second) -> first.hashCode() - second.hashCode(); Comparator<var> comp12 = (var first, var second) -> first.hashCode() - second.hashCode();
The compile error for comp10
and comp11
is the same:
invalid lambda parameter declaration ... (cannot mix 'var' and explicitly-typed parameters)
The compile error for Comparator <var> comp12
is 'var' is not allowed here
, i.e. between the parameterized type angle brackets.
For more information on this topic, see [JEP 323: Local-Variable Syntax for Lambda Parameters](https://openjdk.java.net/jeps/323).
Stay safe, and see you soon! As always, please share your comments and questions.