Variable used in lambda expression should be final or effectively final
时间: 2023-10-26 22:41:19 浏览: 177
When using a lambda expression in Java, any variables referenced inside the lambda expression must be either final or effectively final.
A variable is considered final if it is declared with the `final` keyword and its value cannot be changed after initialization.
A variable is considered effectively final if it is not declared with the `final` keyword, but its value is never changed after initialization.
This requirement exists because the lambda expression captures the value of the variable at the time it is created, and this captured value must remain consistent throughout the lifetime of the lambda expression. By enforcing this rule, Java ensures that the lambda expression behaves predictably and consistently.
If you try to use a non-final variable inside a lambda expression, you will get a compile-time error.
阅读全文