(Typos in Oracle tutorial?) 在 lambda 表达式中访问封闭作用域的局部变量

huangapple go评论77阅读模式
英文:

(Typos in Oracle tutorial?) Accessing local variables of the enclosing scope from a lambda expression

问题

是的,在这个主题上有许多类似的问题,但我想澄清一下官方教程是否应该进行修改。

在Oracle Java教程 https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html 中,

在小节标题“访问封闭范围的局部变量”下面,

它说:

> 由于这个赋值语句,变量 FirstLevel.x 不再是有效的 final。因此,Java编译器会生成一个类似于“从 lambda 表达式引用的局部变量必须是 final 或有效 final”的错误消息,其中 lambda 表达式 myConsumer 尝试访问 FirstLevel.x 变量:
>
> System.out.println("x = " + x);

在上面的段落中,这个 FirstLevel.x 需要修正吗?

我认为它需要修改为 methodInFirstLevel 的参数 x,而不是 FirstLevel.x

因为 lambda 表达式并不引入新的作用域级别,而普通方法(在这种情况下是 methodInFirstLevel)确实创建了一个新的作用域级别。

我理解得对吗?

(我已经尝试在标题和正文中正确描述了这个问题,但如果需要修改这个问题,请告诉我。)

英文:

Yes, there are many similar questions on this topic,
but I want to clarify if the official tutorial should be modified or not.

In the Oracle Java Tutorial https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html,

below the subtitle "Accessing Local Variables of the Enclosing Scope",

it says:

> Because of this assignment statement, the variable FirstLevel.x is not
> effectively final anymore. As a result, the Java compiler generates an
> error message similar to "local variables referenced from a lambda
> expression must be final or effectively final" where the lambda
> expression myConsumer tries to access the FirstLevel.x variable:
>
> System.out.println("x = " + x);

In the above paragraph, doesn't this FirstLevel.x need correction?

I thought it needs to be modified to parameter x of methodInFirstLevel, not FirstLevel.x.

Because, the lambda expression does not introduce a new level of scoping, but a normal method(methodInFirstLevel in this case) does make a new level of scope.

Did I get this wrong?

(I've tried to describe this question correctly in the title & body, but please let me know if this question should be modified.)

答案1

得分: 1

你说得对。我会这样表达:

> 参数变量 x 不再是有效的最终变量。

英文:

You are correct. I would phrase it as:

> the parameter variable x is not effectively final anymore.

huangapple
  • 本文由 发表于 2020年10月25日 15:37:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64521410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定