Variable used in lambda expression should be final or effectively final
时间: 2023-10-12 14:12:57 浏览: 33
In Java, a variable used in a lambda expression should be final or effectively final. This means that the variable should not be modified after it is initialized.
For example:
```
int x = 5;
Function<Integer, Integer> square = (y) -> x * x; // This is valid because x is effectively final
x = 10; // This is not valid because x is no longer effectively final
```
If you try to modify the value of `x` after it is used in the lambda expression, you will get a compilation error. This is because the lambda expression captures the value of the variable at the time the lambda is created, and if the value changes later, it can cause unexpected behavior.
To avoid this issue, it is recommended to use final or effectively final variables in lambda expressions.