JDK-8300691 - final variables in for loop headers should accept updates
Archie Cobbs
archie.cobbs at gmail.com
Wed Oct 2 21:33:16 UTC 2024
After some reflection on this, I'd like to propose the following.
To recap, the problem being addressed is that for() code like this doesn't
compile:
for (int i = 0; i < 10; i++) {
Runnable r = () -> System.out.println(i); // error: "i" is not
effectively final
}
There are two separate ideas proposed in JDK-8300691:
1. Allow for() loop iteration variables to be declared final but still be
mutated in the step
2. Make for() loop iterations variables be effectively final at the start
of the body
Both ideas would both solve the stated problem.
Idea #1 would include an additional benefit, which is that knowing the
variable is final in the body of the loop aids the developer when reasoning
about that code.
However, idea #1 also has some subtle issues (see JDK-8300691 for details)
and is somewhat awkward in creating a "final" variable that can still be
reassigned.
Idea #2 is straightforward and seems to be intuitively agreeable. It solves
the original problem with minimal fuss.
The added benefit of Idea #1 doesn't seem worth the extra mental complexity.
Therefore, I think we should stick with idea #2 for now, i.e., just make
for() loop iterations variables be effectively final at the start of the
body.
Thoughts?
-Archie
--
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20241002/ddd1661f/attachment-0001.htm>
More information about the amber-dev
mailing list