Difference between final and effectively final

后端 未结 14 2833
孤独总比滥情好
孤独总比滥情好 2020-11-22 00:38

I\'m playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know tha

14条回答
  •  别那么骄傲
    2020-11-22 01:06

    According to the docs:

    A variable or parameter whose value is never changed after it is initialized is effectively final.

    Basically, if the compiler finds a variable does not appear in assignments outside of its initialization, then the variable is considered effectively final.

    For example, consider some class:

    public class Foo {
    
        public void baz(int bar) {
            // While the next line is commented, bar is effectively final
            // and while it is uncommented, the assignment means it is not
            // effectively final.
    
            // bar = 2;
        }
    }
    

提交回复
热议问题