本文介绍了为什么“Lambda 表达式中使用的变量必须是最终的或有效的最终"?忽略实例变量的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
}
}
解决方案
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 表达式中使用的变量必须是最终的或有效的最终"?忽略实例变量的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!