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

后端 未结 5 683
陌清茗
陌清茗 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 10:01

    That's because the target type of a method reference or a lambda expression should be a functional interface. Based on that only, runtime will create an instance of a class providing implementation of the given functional interface. Think of lambdas or method references as abstract concept. Assigning it to a functional interface type gives it a concrete meaning.

    Moreover, a particular lambda or method reference, can have multiple functional interfaces as its target type. For example, consider the following lamda:

    int x = 5;
    FunctionalInterface func = (x) -> System.out.println(x);
    

    This lambda is a Consumer of x. In addition to that, any interface with a single abstract method with following signature:

    public abstract void xxx(int value);
    

    can be used as target type. So, which interface would you want runtime to implement, if you assign the lambda to Object type? That is why you've to explicitly provide a functional interface as target type.

    Now, once you got a functional interface reference holding an instance, you can assign it to any super reference (including Object)

提交回复
热议问题