Difference between final and effectively final

后端 未结 14 2805
孤独总比滥情好
孤独总比滥情好 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:12
    public class LambdaScopeTest {
        public int x = 0;        
        class FirstLevel {
            public int x = 1;    
            void methodInFirstLevel(int x) {
    
                // The following statement causes the compiler to generate
                // the error "local variables referenced from a lambda expression
                // must be final or effectively final" in statement A:
                //
                // x = 99; 
    
            }
        }    
    }
    

    As others have said, a variable or parameter whose value is never changed after it is initialized is effectively final. In the above code, if you change the value of x in inner class FirstLevel then the compiler will give you the error message:

    Local variables referenced from a lambda expression must be final or effectively final.

    0 讨论(0)
  • 2020-11-22 01:13

    Effective final topic is described in JLS 4.12.4 and the last paragraph consists a clear explanation:

    If a variable is effectively final, adding the final modifier to its declaration will not introduce any compile-time errors. Conversely, a local variable or parameter that is declared final in a valid program becomes effectively final if the final modifier is removed.

    0 讨论(0)
提交回复
热议问题