gpt4 book ai didi

java - 为 Java 的 lambda 体提供 this 关键字会出现什么问题?

转载 作者:行者123 更新时间:2023-12-02 01:13:32 26 4
gpt4 key购买 nike

考虑以下示例

Consumer<Long> f1 = new Consumer<>() {

@Override
public void accept(Long value) {
if (value < 5) {
this.accept(value + 1); //this refers to the anonymous context.
}
}

}

Consumer<Long> f2 = (value) -> {
if (value < 5) {
this.accept(value + 1); //this refers to outer context and the anonymous function is not referable.
}
};

可以看出this没有为 lambda f2 提供但针对更明确编写的匿名 Consumer 实现给出 f1

为什么会这样呢?提供this的语言设计难度是什么?对于 lambda 体?

最佳答案

Java Language Specification 15.27.2 says :

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).

The transparency of this (both explicit and implicit) in the body of a lambda expression - that is, treating it the same as in the surrounding context - allows more flexibility for implementations, and prevents the meaning of unqualified names in the body from being dependent on overload resolution.

Practically speaking, it is unusual for a lambda expression to need to talk about itself (either to call itself recursively or to invoke its other methods), while it is more common to want to use names to refer to things in the enclosing class that would otherwise be shadowed (this, toString()). If it is necessary for a lambda expression to refer to itself (as if via this), a method reference or an anonymous inner class should be used instead.

关于java - 为 Java 的 lambda 体提供 this 关键字会出现什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59006737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com