版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lastsweetop/article/details/82796392
在早期的版本中,本地类,匿名类访问本地变量都需要是final的。
但是1.8版本中,本地类和匿名类,还有lambda表达式访问本地变量已经不用声明为final了,仅仅是不用明确写为final,其实还是final的,这种不明确性可以称之为effectively final,也就是你声明的是一个非final的变量,但是你只要不改变它就可以了。
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;
Consumer<Integer> myConsumer = (y) ->
{
System.out.println("x = " + x); // Statement A
System.out.println("y = " + y);
System.out.println("this.x = " + this.x);
System.out.println("LambdaScopeTest.this.x = " +
LambdaScopeTest.this.x);
};
myConsumer.accept(x);
}
一旦放开x=99
的注释就会报错。
local variables referenced from a lambda expression must be final or effectively final