Difference between final and effectively final

后端 未结 14 3099
孤独总比滥情好
孤独总比滥情好 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 00:54

    This variable below is final, so we can't change it's value once initialised. If we try to we'll get a compilation error...

    final int variable = 123;
    

    But if we create a variable like this, we can change it's value...

    int variable = 123;
    variable = 456;
    

    But in Java 8, all variables are final by default. But the existence of the 2nd line in the code makes it non-final. So if we remove the 2nd line from the above code, our variable is now "effectively final"...

    int variable = 123;
    

    So.. Any variable that is assigned once and only once, is "effectively final".

提交回复
热议问题