问题描述
我正在研究java 8流,我唯一的问题是理解lambdas是为什么lambdas中的有效最终警告被忽略的实例(和静态)变量。我似乎无法在网上找到任何参考,因为大多数网页只会谈论有效最终的定义。
I'm studying java 8 streams and the only problem I have is understanding lambdas is why the effectively final warning in lambdas is ignored for instance(and static) variables. I can't seem to find any reference to it online, as most pages will just talk about the definition of being "effectively final".
public class LambdaTest {
int instanceCounter = 0;
public void method() {
int localCounter = 0;
instanceCounter = 5; //Re-assign instance counter so it is no longer effectively final
Stream.of(1,2,3).forEach(elem -> instanceCounter++); //WHY DOES THE COMPILER NOT COMPLAIN HERE
Stream.of(1,2,3).forEach(elem -> localCounter++); //Does not compile because localCounter is not effectively final
}
}
推荐答案
我们倾向于忘记 instanceCounter
实际上是 this.instanceCounter
,你是捕获这个
哪个好,有效最终。至于为什么这是需要的,答案显然是
We tend to forget that instanceCounter
is actually this.instanceCounter
, you are capturing this
which is well, effectively final. As to why this is needed, the answer is obviously here
这篇关于为什么“Lambda表达式中使用的变量必须是最终的或有效的最终”?警告忽略实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!