Difference between final and effectively final

后端 未结 14 2807
孤独总比滥情好
孤独总比滥情好 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条回答
  •  -上瘾入骨i
    2020-11-22 01:00

    When a lambda expression uses an assigned local variable from its enclosing space there is an important restriction. A lambda expression may only use local variable whose value doesn't change. That restriction is referred as "variable capture" which is described as; lambda expression capture values, not variables.
    The local variables that a lambda expression may use are known as "effectively final".
    An effectively final variable is one whose value does not change after it is first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error.
    Let's see it with an example, we have a local variable i which is initialized with the value 7, with in the lambda expression we are trying to change that value by assigning a new value to i. This will result in compiler error - "Local variable i defined in an enclosing scope must be final or effectively final"

    @FunctionalInterface
    interface IFuncInt {
        int func(int num1, int num2);
        public String toString();
    }
    
    public class LambdaVarDemo {
    
        public static void main(String[] args){             
            int i = 7;
            IFuncInt funcInt = (num1, num2) -> {
                i = num1 + num2;
                return i;
            };
        }   
    }
    

提交回复
热议问题