[External] : Effectively final loop counter (was: Are templated string embedded expressions "method parameters" or "lambdas"?)

John Rose john.r.rose at oracle.com
Tue Nov 2 03:37:02 UTC 2021

On Oct 31, 2021, at 6:47 AM, Brian Goetz <brian.goetz at oracle.com> wrote:
>> This is a somewhat separate topic but I would be glad to see some
>> improvement here with respect to good old for loops, as I often saw
>> copying to a new variable for the sake of lambda capture inside the
>> loop.
> As a separate separate topic, I'd like to make good-old-for-loops more of a thing of the past.
> For example, there's a reasonable stacking of features atop Valhalla that gets us to:
>     for (int i : 0..<n) { ... }
> with no performance overhead (e.g., no Iterator creation.)
> My point is not to dive into the stack of features that get us there, but to point out that the "enhanced" for loop, which is currently extremely limited, has some legs to be generalized to the point where old-school for loops might look more quaint.  So I'd rather spend energy on that, rather than rehabilitating the borrowed-from-C for loop.

That too.  My previous message is my best take for the cheapest
way to inject a little more life and relevance into old-for.

Another way to breath life into old-for would be to allow
non-final variables to be shadowed by final variables of the
same name and value, with a very restricted redeclaration
of that name:

for (int i = 0; i < a.length; i++) { final i; foo( () -> i ); }


for (int i = 0; i < a.length; i++) { 
  __Synthetic final var i$final = i;
  foo( () -> i$final ); }

In this case, the magic declaration “final var i = i” switches
i from mutable in the header to non-mutable in the body.
Such magic is not specific to loops but can be used in other
places also, where mutable bindings don’t conform to
“effectively final” rules, but where at a particular point
all downstream uses are in fact frozen.

More information about the amber-spec-experts mailing list