Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8341785 Treat Loop Variables as Effectively Final in the Bodies of All for() Loops
  3. JDK-8341782

Allow lambda capture of basic for() loop variables as with enhanced for()

XMLWordPrintable

    • Icon: Sub-task Sub-task
    • Resolution: Won't Fix
    • Icon: P4 P4
    • None
    • None
    • tools
    • None
    • generic
    • generic

      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

            acobbs Archie Cobbs
            acobbs Archie Cobbs
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: