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

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

    To everyone who is saying this is impossible, undesired, or unwanted, I just want to point out that Scala can infer the lambda's type by specifying only the argument type:

    val predicateVar = (apple: Apple) => apple.getColor().equals("red")
    

    And in Haskell, because getColor would be a standalone function not attached to an object, and because it does full Hindley-Milner inference, you don't need to specify even the argument type:

    predicateVar = \apple -> getColor apple == "red"
    

    This is extraordinarily handy, because it's not the simple types that are annoying for programmers to explicitly specify, it's the more complex ones.

    In other words, it's not a feature in Java 10. It's a limitation of their implementation and previous design choices.

提交回复
热议问题