Search code examples
javalambdajava-11type-inference

Why should I use local-variable type Inference for lambda parameters if I can skip it?


Java 11 introduced local-variable type Inference for lambda parameters. For example:

Stream.of("a", "b", "c").map((var a) -> "ok")

My question is: why should I use it, if I can skip it. For example:

Stream.of("a", "b", "c").map(a -> "ok")

?


Solution

  • The JEP 323 states the following goal:

    • Align the syntax of a formal parameter declaration in an implicitly typed lambda expression with the syntax of a local variable declaration.

    And it states as motiviation:

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

        (x, y) -> x.process(y)    // implicitly typed lambda expression
    

    Java SE 10 makes implicit typing available for local variables:

        var x = new Foo();
        for (var x : xs) { ... }
        try (var x = ...) { ... } catch ...
    

    For uniformity with local variables, we wish to allow 'var' for the formal parameters of an implicitly typed lambda expression:

        (var x, var y) -> x.process(y)   // implicit typed lambda expression
    

    One benefit of uniformity is that modifiers, notably annotations, can be applied to local variables and lambda formals without losing brevity:

        @Nonnull var x = new Foo();
        (@Nonnull var x, @Nullable var y) -> x.process(y)
    

    Should you use it if you can skip it?

    There might be contexts where you are required to use it (if you work in a project with a rigid coding convention that mandates the use). In other contexts it is probably opinion based.

    My specific opinion: if you don't need it then don't use it.

    • You will need it if you need to annotate the lambda parameters
    • otherwise leave it out