Auto indexing improved for() loops
P Holder
pholder at gmail.com
Tue Dec 5 09:00:50 UTC 2023
I'm participating in Advent of Code 2023 using Java. It reminds me how I
frequently wish I could have an index in a modern for loop without having
to resort to using the old/traditional for loop. Now that the JEP 456
Unnamed Variables & Patterns is progressing nicely I can see how it could
be used implicitly to grant my wish.
Instead of writing:
final String[] strings = getSomeStrings();
int index = 0;
for (final String str : strings)
{
// use the str and the index
index++;
}
and risking the chance I may forget to place the index++ ... I would rather
have something like:
final String[] strings = getSomeStrings();
for (int index, final String str : strings)
{
// use the str and the index
}
where the new part "int index" is optional, and the compiler could treat it
like "int _" if not specified. Of course it could also be long, one
assumes.
I do realize it's merely syntactic sugar and I do know how to write the
code I need, but it does surprise me the number of times I end up writing
old for loops simply because I could use the index, but otherwise know
doing it the modern way is cleaner and more expressive, if only I had the
index too.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231205/759f91cd/attachment-0001.htm>
More information about the amber-dev
mailing list