JDK-8300691 - final variables in for loop headers should accept updates
Ron Pressler
ron.pressler at oracle.com
Wed Oct 23 12:00:23 UTC 2024
> On 23 Oct 2024, at 11:14, Maurizio Cimadamore <maurizio.cimadamore at oracle.com> wrote:
>
> My subjective opinion here is that, if this principle is important (and, as John mentioned, it was very painfully front and center when inner classes were first added to the language), giving this principle up to allow capture in an extra 20-30 imperative loops (in an entire codebase) doesn’t look a great deal. That is, reducing asymmeties between counted loops and for-each loop comes at a price: now capture variables no longer mean the same thing they do in their non-captured context.
I think this is a matter of perspective.
Suppose you have:
for (int x : List.of(0, 1, 2)) { … }
and
for (int x = 0; x < 3; x++) { … }
In both situations, the capture would fail if we reassign x inside the loop’s body (whether inside the lambda or outside it), and in both situations `x` will be bound to different values over time inside the loop’s body but outside the lambda, but not inside it, where it is snapshotted (assuming it is kept somewhere and evaluated after some time).
That x really means something subtly different in the foreach loop and the classic loop is more of an implementation detail. I don’t know the history of that choice, and it did predate lambda, but if it was made to allow a final index to be captured in an index class, then capturability is the motivation for that detail.
— Ron
More information about the amber-dev
mailing list