JDK-8300691 - final variables in for loop headers should accept updates

Clement Cherlin ccherlin at gmail.com
Thu Jan 9 19:57:30 UTC 2025


On Thu, Dec 19, 2024 at 9:19 AM Archie Cobbs <archie.cobbs at gmail.com> wrote:

> On Wed, Dec 11, 2024 at 2:25 PM Archie Cobbs <archie.cobbs at gmail.com>
> wrote:
>
>> There is a (small) language change under consideration on amber-dev, and
>> opinions have been expressed in multiple directions, so I'm turning to this
>> list for hopefully some authoritative adjudication.
>>
>
> Since I didn't hear an overwhelming roar of approval, I'll shelve this for
> now. The issues and PR will still be there if/when we want to take this up
> again in the future.
>
> Thanks,
> -Archie
>
> --
> Archie L. Cobbs
>

I know I'm late on this, but I think the right way to address deficiencies
like this in old-style for loops is to make enhanced for loops better in
ways that reduce/eliminate the need for old-style for loops. That approach
has been very successful with enhanced switch.

A simple and efficient way to use a simple range or arithmetic progression
in enhanced for loops could replace 99% of uses of old-style for loops.

Since there's no such thing as PrimitiveIterable, I presume that will
require primitive specialization (JEP 218) from Valhalla. Primitive
specialization will make it possible to use Iterable<int> instead of
Iterable<Integer>.

A second, orthogonal improvement would be ImmutableIterator and
ImmutableIterable interfaces that the enhanced for loop understands, making
it possible to write value-based iterators.

In addition to being able to lambda-capture the loop variable, "for (final
int i : Range.closed(0, 9)) {...}" is much easier to read (and less
vulnerable to off-by-one errors) than the old-style for loop "for (int i =
0; i <= 9; ++i) {...}"

Cheers,
Clement
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-spec-observers/attachments/20250109/00702c7a/attachment-0001.htm>


More information about the amber-spec-observers mailing list