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

后端 未结 5 696
陌清茗
陌清茗 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:55

    I suspect this is a purely academical question, since I can't see any real-life use case for this. Nevertheless, I am pretty sure that it has to do with Stream::of being a lambda expression. You could also not do this:

    Object of_ref = list -> Stream.of(list);
    

    I speculate that an accurate return type tells the compiler which FunctionalInterface it being used. Without this information it is impossible for the compiler to resolve the Lambda expression correctly and unambiguously.

提交回复
热议问题