Note - This issue is split off from JDK-8300691 which discusses two possible language changes; this issue represents one of the changes described in that issue ("change #2").
Allow this code, which doesn't currently compile, to compile:
for (int i = 1; i <= 3; i++) {
Runnable r = () -> System.out.println(i); // error: "i" is not effectively final
}
just like this code, which does compile:
for (int i : new int[] { 1, 2, 3 }) {
Runnable r = () -> System.out.println(i); // ok
}
In other words, for the purposes of whether to allow a lambda, nested class, or switch case guard to capture a basic for() loop variable, treat a loop that looks like this:
for (int i = 1; i <= 3; i++) {
// statements involving i...
}
as if it were written like this:
for (int i = 1; i <= 3; i++) {
int i$ = i;
// statements involving i$...
}
Amber-dev discussion: https://mail.openjdk.org/pipermail/amber-dev/2024-September/008921.html
Allow this code, which doesn't currently compile, to compile:
for (int i = 1; i <= 3; i++) {
Runnable r = () -> System.out.println(i); // error: "i" is not effectively final
}
just like this code, which does compile:
for (int i : new int[] { 1, 2, 3 }) {
Runnable r = () -> System.out.println(i); // ok
}
In other words, for the purposes of whether to allow a lambda, nested class, or switch case guard to capture a basic for() loop variable, treat a loop that looks like this:
for (int i = 1; i <= 3; i++) {
// statements involving i...
}
as if it were written like this:
for (int i = 1; i <= 3; i++) {
int i$ = i;
// statements involving i$...
}
Amber-dev discussion: https://mail.openjdk.org/pipermail/amber-dev/2024-September/008921.html
- csr for
-
JDK-8341783 Allow lambda capture of basic for() loop variables as with enhanced for()
-
- Closed
-
- relates to
-
JDK-8300691 final variables in for loop headers should accept updates
-
- Open
-
- links to
-
Review(master) openjdk/jdk/21415