RFR: 8341782: Allow lamba capture of basic for() loop variables as with enhanced for()
Maurizio Cimadamore
mcimadamore at openjdk.org
Wed Oct 9 09:16: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 2733:
> 2731: try {
> 2732: scan(tree.body);
> 2733: for (int adr = forLoopVarMin; adr < forLoopVarMax; adr++) {
Question: since we already have a dedicated flag for loop variables - could we set the flag on _all_ loop variables (before the body), and then remove it in `letInit` (same as we do for effectively final flag) ? This way, at the end of the loop, the variables that still have the flag set will be the ones that have not been reassigned, correct?
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/21415#discussion_r1793165126
More information about the compiler-dev
mailing list