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

前端 未结 7 1092
一整个雨季
一整个雨季 2021-02-01 12:10

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 e

相关标签:
7条回答
  • 2021-02-01 12:50

    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.

    0 讨论(0)
提交回复
热议问题