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

前端 未结 7 1215
一整个雨季
一整个雨季 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:30

    As several people have already mentioned, what type should var infer and why should it?

    The statement:

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

    is ambiguous and there is no valid reason why the compiler should pick Function over Predicate or vice versa assuming the apple identifier in the lambda represents an Apple isntance.

    Another reason is that a lambda in its own doesn't have a speakable type hence there is no way for the compiler to infer it.

    Also, "if this was possible" imagine the overhead as the compiler would have to go through all the functional interfaces and determine which functional interface is the most appropriate each time you assign a lambda to a var variable.

提交回复
热议问题