Difference between final and effectively final

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

    ... starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.

    For example, suppose that the variable numberLength is not declared final, and you add the marked assignment statement in the PhoneNumber constructor:

    public class OutterClass {  
    
      int numberLength; // <== not *final*
    
      class PhoneNumber {
    
        PhoneNumber(String phoneNumber) {
            numberLength = 7;   // <== assignment to numberLength
            String currentNumber = phoneNumber.replaceAll(
                regularExpression, "");
            if (currentNumber.length() == numberLength)
                formattedPhoneNumber = currentNumber;
            else
                formattedPhoneNumber = null;
         }
    
      ...
    
      }
    
    ...
    
    }
    

    Because of this assignment statement, the variable numberLength is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class PhoneNumber tries to access the numberLength variable:

    http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html

    http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

提交回复
热议问题