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

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

    This has nothing to do with var. It has to do with whether a lambda has a standalone type. The way var works is that it computes the standalone type of the initializer on the RHS, and infers that.

    Since their introduction in Java 8, lambda expressions and method references have no standalone type -- they require a target type, which must be a functional interface.

    If you try:

    Object o = (String s) -> s.length();
    

    you also get a type error, because the compiler has no idea what functional interface you intend to convert the lambda to.

    Asking for inference with var just makes it harder, but since the easier question can't be answered, the harder one cannot either.

    Note that you could provide a target type by other means (such as a cast) and then it would work:

    var x = (Predicate) s -> s.isEmpty();
    

    because now the RHS has a standalone type. But you are better off providing the target type by giving x a manifest type.

提交回复
热议问题