Explicit captures in lambda expression

Archie Cobbs archie.cobbs at gmail.com
Tue Jan 7 16:30:03 UTC 2025


On Tue, Jan 7, 2025 at 9:54 AM Attila Kelemen <attila.kelemen85 at gmail.com>
wrote:

> I didn't mean for the lambda to unassign the variable, I was just lazy to
> write it out exactly: I meant that the variable is DU after lambda if we
> assume that the variable is DU at the point of capturing (basically we
> pretend that the variable is DU even though it is actually DA). Consider
> this code (doesn't compile, but I think it should).
>
> int x = 5;
> if (test) x = 6;
> new Thread(() -> { System.out.println("Hello: " + x) }).start();
>
> I don't really see why this shouldn't compile.
>

In the for() loop discussion, we used the phrase "not reassigned" for this
concept.

That thread ("JDK-8300691 - final variables in for loop headers should
accept updates") has a bunch of discussion about the idea.

One wrinkle is that properly defining "not reassigned" requires properly
defining "before" and "after", and for() loops complicate that definition.

For example if you have this:

for (int i = 1; i <= 3; i++) {
    Runnable r = () -> System.out.println(i);   // allow this?
}

The "i++" happens "after" the capture - assuming your definition of "after"
is based on control flow rather than lexical position - which means we'd
need a special exception for it, etc.

John Rose had some relevant thoughts/discussion here (re: "final
shadowing"):
https://mail.openjdk.org/pipermail/amber-dev/2024-October/008996.html

-Archie

-- 
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20250107/1dec986b/attachment-0001.htm>


More information about the amber-dev mailing list