Local-Variable Syntax for Lambda Parameters

Introduced in Java 11 via JEP 323, this feature allows the var keyword (originally introduced for local variables in Java 10) to be used in lambda parameter declarations. It enables type inference for lambda parameters, reducing verbosity and aligning lambda syntax with local variable declarations.

Syntax

You can use var instead of explicit types in lambda parameters:

(var x, var y) -> x + yCode language: JavaScript (javascript)

This is equivalent to:

(int x, int y) -> x + y

The compiler infers the types based on the target functional interface.

Key Features

  1. Type Inference: The compiler determines parameter types from the context (e.g., the functional interface the lambda is assigned to).
  2. Annotations Support: var allows annotations on lambda parameters without requiring explicit types, e.g.:
(@NonNull var x, @NonNull var y) -> x + yCode language: JavaScript (javascript)

Rules and Restrictions

  • All or None: You must use var for all parameters or none. Mixing is not allowed, e.g., (var x, int y) is invalid.
  • Parentheses Required: For multiple parameters, parentheses are mandatory, e.g., (var x, var y).
  • Single Parameter: For a single parameter, parentheses are still required with var, e.g., (var x) -> x * 2 (not var x -> x * 2).
  • No Default Values: Lambda parameters cannot have default values, regardless of var.

Example in Java 11+

import java.util.function.BiFunction;

public class LambdaVarExample {
    public static void main(String[] args) {
        // Lambda with var
        BiFunction<Integer, Integer, Integer> add = (var x, var y) -> x + y;
        System.out.println(add.apply(3, 4)); // Output: 7

    }
}Code language: PHP (php)

When to Use

  • Use var to make lambda expressions more concise, especially when types are clear from context.
  • It’s particularly helpful for adding annotations without verbose type declarations.
  • Avoid var if explicit types improve readability or in cases where type inference might confuse maintainers.
The local-variable syntax for lambda parameters in Java 11, using the var keyword, simplifies lambda expressions by allowing type inference for parameters. It reduces verbosity, aligns lambda syntax with local variable declarations, and supports annotations without explicit types. For example, (var x) -> System.out.println(x) is concise and clear. This feature, introduced in Java 11 via JEP 323, remains unchanged in later versions, is widely adopted for cleaner code, and is especially useful for annotated parameters. However, use explicit types when clarity is needed, and ensure compatibility with Java 11 or later.
Scroll to Top