关于 java-8 语法的简单问题。为什么 JLS-8 限制如下表达式:
Simple question about java-8 syntax. Why does JLS-8 restrict such expressions like:
Object of_ref = Stream::of; // compile-time error并且仅允许以下内容:
java.util.function.Function of_ref = Stream::of; Object obj = of_ref; // compiles ok?
推荐答案这是因为方法引用或lambda表达式的目标类型应该是一个功能接口。仅基于此,运行时将创建提供给定功能接口的实现的类的实例。将lambdas或方法引用视为 abstract 概念。将其分配给功能接口类型赋予其具体含义。
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.
此外,特定的lambda或方法引用可以具有多个功能接口作为其目标类型。例如,考虑以下lamda:
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);此lambda是消费者 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);可用作目标类型。那么,如果将lambda分配给 Object 类型,那么您希望运行时实现哪个接口?这就是为什么你要明确地提供一个功能接口作为目标类型的原因。
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)
更多推荐
为什么我不能直接将方法引用分配给Object类型的变量?
发布评论