Learnitweb

Local-Variable Syntax for Lambda Parameters

1. Introduction

Local-Variable syntax for Lambda parameters was introduced as JEP 323. This change allows var to be used when declaring the formal parameters of implicitly typed lambda expressions. The goal of this change is to align the syntax of a formal parameter declaration in an implicitly typed lambda expression with the syntax of a local variable declaration.

Starting Java 11, reserved type name var is allowed for formal parameters of implicitly typed lambda expressions.

Let us see an example.

(var s1, var s2) -> s1.myMethod(s2)

is equivalent to:

(s1, s2) -> s1.myMethod(s2)

A lambda expression may be implicitly typed, where the types of all its formal parameters are inferred:

(s1) -> s1.substring(0, s1.length() - 1); // implicitly typed lambda expression

Java SE 10 made implicit typing available for local variables:

var x = new Foo();

For uniformity with local variables, it is desirable to allow var for the formal parameters of an implicitly typed lambda expression:

(var s1) -> s1.substring(0, s1.length() - 1); // implicitly typed lambda expression

2. Local Variable Syntax for Lambda Parameters

Consider the following lambda expression:

(String s1, String s2) -> s1 + s2

This could be written using type inference like

(String s1, String s2) -> s1 + s2

We should be able to write this lamda expression like

(var s1, var s2) -> s1 + s2

Java 10 didn’t support this but Java 11 does. This change of Java 11 makes the usage of var uniform in both local variables and lambda parameters.

3. Benefits

The benefit of uniformity is that the modifiers, specially annotations can be applied to lambda formal parameters.

@Nonnull var x = new Foo();
(@Nonnull var s1) -> s1.substring(0, s1.length() - 1);

We cannot use such modifiers and annotations without specifying the types.

4. Limitation

An implicitly typed lambda expression must use var for all its formal parameters or for none of them. So following are not illegal:

(var s1, s2) -> s1.myMethod(s2) // either you provide 'var' for all or do not provide for all
(var s1, int s2) -> s1.myMethod(s2)  // Cannot mix 'var' and manifest types

Parentheses can not be skipped in case of var. So following is illegal:

var s1 -> s1.substring(0, s1.length() - 1); // illegal as no parentheses

The legal way to write this is

(var s1) -> s1.substring(0, s1.length() - 1); // illegal as no parentheses

5. Conclusion

In this short tutorial, we discussed in Java 11 and saw how we can use local variable syntax for lambda parameters.