variable user in lambda expression should be final or effectively final
时间: 2023-10-12 14:13:45 浏览: 105
编译器说 Lambda 表达式中的变量必须是 final 的,我偏不信
In a lambda expression, any local variable that is being accessed from within the lambda expression must either be declared as `final` or must be effectively final.
An effectively final variable is a variable whose value is not changed after it is initialized. For example:
```
int x = 5;
Consumer<Integer> c = (y) -> System.out.println(x + y);
```
In this case, `x` is effectively final because its value is not changed after it is initialized.
If you try to modify the value of a variable that is not final or effectively final within a lambda expression, you will get a compilation error.
This restriction is in place to ensure that the lambda expression does not depend on mutable state, which can make the code harder to reason about and lead to subtle bugs.
阅读全文