Java 11

Java 11 – Var in Lambda

Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.

(@NonNull var value1, @Nullable var value2) -> value1 + value2

Consider the following program −

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@interface NonNull {}

public class APITester {
   public static void main(String[] args) {		
      List<String> tutorialsList = Arrays.asList("Java", "HTML");

      String tutorials = tutorialsList.stream()
         .map((@NonNull var tutorial) -> tutorial.toUpperCase())
         .collect(Collectors.joining(", "));

      System.out.println(tutorials);
   }
}

Limitations

There are certain limitations on using var in lambda expressions.

1. var parameters cannot be mixed with other typed parameters. Following will throw compilation error.

(var a, String b) -> a.toLowerCase() + b.toLowerCase();

Error:

'var' cannot be mixed with non-var parameters

2. var parameters cannot be mixed with other parameters. Following will throw compilation error.

(var a, b) -> a.toLowerCase() + b.toLowerCase();

Error:

Syntax error on token "var", ( expected after this token
	Syntax error on token "->", invalid AssignmentOperator
	Syntax error, insert ")" to complete Expression

3. var parameters can only be used with parenthesis. Following will throw compilation error.

var a -> a.toLowerCase();

Error:

Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
	Syntax error, insert ";" to complete LocalVariableDeclarationStatement
	Syntax error, insert "AssignmentOperator Expression" to complete Expression

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs