Local variable row defined in an enclosing scope must be final or effectively final
时间: 2023-07-17 09:01:04 浏览: 364
The error message "Local variable row defined in an enclosing scope must be final or effectively final" is related to the concept of closures in Java. In Java, when you define a local variable inside an enclosing scope (such as a method or a loop), and you want to use that variable inside an anonymous inner class or lambda expression, the variable needs to be either final or effectively final.
A variable is effectively final if its value is not changed after initialization. If you try to modify the value of a non-final or non-effectively final variable inside an inner class or lambda expression, you will encounter this error.
To resolve this issue, you can either make the variable "row" final or effectively final by not modifying its value after initialization, or you can use a different approach, such as using a different variable or passing the value of "row" to the inner class or lambda expression explicitly.
Here's an example of making the variable final:
```java
final int row = 10;
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Row: " + row);
}
};
```
And here's an example of effectively final variable:
```java
int row = 10;
Runnable runnable = () -> {
System.out.println("Row: " + row);
};
```
Remember, if you modify the value of the "row" variable after its initialization, you will encounter the mentioned error.
阅读全文