为什么“Lambda 表达式中使用的变量必须是最终的或有效的最终"?忽略实例变量的警告变量、表达式、实例、有效

2023-09-08 08:44:16 作者:每一天都

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
    }
}

解决方案 什么是Lambda

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