Variable used in lambda expression should be final or effectively final
时间: 2023-10-14 21:27:51 浏览: 56
In Java, when using a lambda expression, any variable that is used inside the lambda expression must be final or effectively final. This means that the variable cannot be modified after it has been initialized.
Effectively final means that the variable is not explicitly declared as final, but its value is not changed after initialization. For example:
```
int x = 5;
Function<Integer, Integer> func = (y) -> x + y; // x is effectively final
```
In this example, `x` is not declared as final, but its value is not changed after initialization, so it is effectively final and can be used in the lambda expression.
If a variable is not final or effectively final, the compiler will give an error when trying to use it inside a lambda expression. This is because lambda expressions are implemented as anonymous inner classes, and the variable's value needs to be captured and stored inside the class. If the variable is not final or effectively final, its value could change, which would break the logic of the lambda expression.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)