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

前端 未结 7 1111
一整个雨季
一整个雨季 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条回答
  •  旧时难觅i
    2021-02-01 12:45

    In a nutshell, the types of a var and lambda expression both need inference, but in opposite way. The type of a var is inferred by the initializer:

    var a = new Apple();
    

    The type of a lambda expression is set by the context. The type expected by the context is called the target type, and is usually inferred by the declaration e.g.

    // Variable assignment
    Function l = (n) -> 2 * n;
    // Method argument 
    List map(List list, Function fn){
        //...
    }
    map(List.of(1, 2, 3), (n) -> 2 * n);
    // Method return 
    Function foo(boolean flag){
        //...
        return (n) -> 2 * n;
    }
    

    So when a var and lambda expression are used together, the type of the former needs to be inferred by the latter while the type of the latter needs to be inferred by the former.

    var a = (n) -> 2 * n;
    

    The root of this dilemma is Java cannot decide the type of a lambda expression uniquely, which is further caused by Java's nominal instead of structural type system. That is, two types with identical structures but different names are not deemed as the same, e.g.

    class A{
        public int count;
        int value(){
            return count;
        }
    }
    
    class B{
        public int count;
        int value(){
            return count;
        }
    }
    
    Function
    Predicate
    

提交回复
热议问题