95. LVTI and lambdas

The problem with using LVTI and lambdas is that the concrete type cannot be inferred. Lambdas and method reference initializers are not allowed. This statement is part of var limitations; therefore, lambda expressions and method references need explicit target types.

For example, the following snippet of code will not compile:

// Does not compile
// lambda expression needs an explicit target-type
var incrementX = x -> x + 1;

// method reference needs an explicit target-type
var exceptionIAE = IllegalArgumentException::new;

Since var cannot be used, these two snippets of code need to be written as follows:

Function<Integer, Integer> incrementX = x -> x + 1;
Supplier<IllegalArgumentException> exceptionIAE
= IllegalArgumentException::new;

But in the context of lambdas, Java 11 allows us to use var in lambda parameters. For example, the following code is working in Java 11 (more details can be found in JEP 323: Local-Variable Syntax for Lambda Parameters at https://openjdk.java.net/jeps/323):

@FunctionalInterface
public interface Square {
int calculate(int x);
}

Square square = (var x) -> x * x;

However, keep in mind that the following will not work:

var square = (var x) -> x * x; // cannot infer
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.5.57