Why can't the var keyword in Java be assigned a lambda expression?

hi.nitish :

It is allowed to assign var in Java 10 with a string like:

var foo = "boo";

While it is not allowed to assign it with a lambda expression such as:

var predicateVar = apple -> apple.getColor().equals("red");

Why can't it infer a lambda or method reference type when it can infer the rest like String, ArrayList, user class, etc.?

Jorn Vernee :

From the Local-Variable Type Inference JEP:

The inference process, substantially, just gives the variable the type of its initializer expression. Some subtleties:

  • The initializer has no target type (because we haven't inferred it yet). Poly expressions that require such a type, like lambdas, method references, and array initializers, will trigger an error.

Because a lambda expression by itself does not have a type, it can not be inferred for var.


... Similarly, a default rule could be set.

Sure, you can come up with a way to work around this limitation. Why the developers made the decision not to do that is really up to speculation, unless someone who was part of the decision making can answer here. (Update: answered here.) If you're interested anyway, you could ask about it on one of the openjdk mailing lists: http://mail.openjdk.java.net/mailman/listinfo

If I were to guess, they probably didn't want to tie lambda inference in the context of var to a specific set of functional interface types, which would exclude any third party functional interface types. A better solution would be to infer a generic function type (i.e. (Apple) -> boolean) that can than be converted to a compatible functional interface type. But the JVM does not have such function types, and the decision to not implement them was already made during the project that created lambda expressions. Again if you're interested in concrete reasons, ask the devs.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=423467&siteId=1