RFR: 8341782: Allow lamba capture of basic for() loop variables as with enhanced for()
Maurizio Cimadamore
mcimadamore at openjdk.org
Tue Oct 8 21:21:57 UTC 2024
On Tue, 8 Oct 2024 19:53:56 GMT, Archie Cobbs <acobbs at openjdk.org> wrote:
> This PR changes the compiler to allow basic `for()` loop iteration variables to be captured by lambdas in the loop body, even when their "effectively final" status is invalidated by modifications in the header of the loop.
>
> This allows code like this to compile:
>
> for (int i = 1; i <= 3; i++) {
> Runnable r = () -> System.out.println(i);
> }
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java line 2729:
> 2727: uninitsSkip.inclRange(firstadr, nextadr);
> 2728: }
> 2729: final Bits reassignedInForLoopBodyPrev = reassignedInForLoopBody;
My memory of this code is a bit rusty, so please bear with me... I seem to recall we mark all variables as effectively final, and then "unmark" them if see see them in `letInit`. If this is correct, could we simply re-force the effectively final flag of a loop variable before the loop body?
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/21415#discussion_r1792523413
More information about the compiler-dev
mailing list