"providing a delegate" 在 lambda 表达式的上下文中意味着什么?

What does "providing a delegate" mean in the context of a lambda expression?

我在 Java 中将 :: 运算符定义为:

The double colon (::) operator, i.e. method reference operator, is used to call a method by referring to it with the help of its class directly. They behave the same as lambda expressions. The only difference is this uses direct reference to the method by name instead of providing a delegate to the method.

谁能帮忙解释一下最后一部分 - 即 “而不是向方法提供委托”。这部分是什么意思?

意思是你可以引用一个方法,比如像这样:

myList.forEach(System.out::println);

... 而不是编写 lambda 并调用方法:

myList.forEach(i -> System.out.println(i));

Delegation 是当一个对象有一个方法时,它只是调用另一个对象上的等效方法;例如,在下面的 class 中,方法 foo 被委托给对象 obj:

class Example {
    private final Bar obj;
    public Example(Bar obj) {
        this.obj = obj;
    }
    public Baz foo(Qux x) {
        return obj.foo(x);
    }
}

x -> obj.foo(x) 这样的 lambda 表达式在语法上类似于 return obj.foo(x);,lambda 表达式的求值创建一个对象,该对象的方法将 foo 方法委托给对象 obj,在语义上类似于 new Example(obj)。所以这是委托的例子。

当然,obj::foo (语义上)创建一个对象,该对象的方法将 foo 方法委托给对象 obj .所以你引用的文字似乎值得商榷;引用确实至少说行为是相同的,所以也许作者的意思是 lambda 在语法上类似于委托,而方法引用则不然(因为它在 point-free style 中)。至少,这似乎是引用 的意思 .


为了抢先解决关于 lambda 表达式和方法引用是否真的创建对象的争论:如果您使用调试器,那么您可能会发现一些实现细节表明情况并非如此,但是 Java 语言规范权威地说,那 (§15.27.4)

At run time, evaluation of a lambda expression is similar to evaluation of a class instance creation expression, insofar as normal completion produces a reference to an object. [...] Either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced.

和(§15.13.3)

At run time, evaluation of a method reference expression is similar to evaluation of a class instance creation expression, insofar as normal completion produces a reference to an object. [...] either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced.