Why can I not assign a method reference directly to a variable of Object type?

后端 未结 5 677
陌清茗
陌清茗 2020-12-09 09:43

Simple question about java-8 syntax. Why does JLS-8 restrict such expressions like:

Object of_ref = Stream::of;  // compile-time er         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 09:53

    The key point is that there are no "function types" in Java. A lambda expression doesn't have a "type" by itself -- it can be typed to any functional interface whose sole method's signature matches the lambda. Therefore, a lambda's type is based on the type provided by its context. You must provide a functional interface as the context for it to get a type.

    It is instructive to consider the same issue but for anonymous classes. Although there are implementation differences between lambdas and anonymous classes, semantically, lambdas are essentially equivalent to a subset of anonymous classes, and a lambda expression can always be converted to an equivalent anonymous class creation expression.

    When you write:

    Function> of_ref = Stream::of;
    

    it is equivalent to something like the following using anonymous classes:

    Function> of_ref = new Function>() {
        Stream apply(T t) {
            return Stream.of(t);
        }
    };
    

    Now consider

    Object of_ref = Stream::of;
    

    what is the equivalent with anonymous classes?

    Object of_ref = new [**What goes here?**]() {
        [**What method signature goes here?**] {
            return Stream.of(t);
        }
    };
    

    You see why it doesn't make sense -- we don't know what type to use as the base class of the anonymous class.

提交回复
热议问题