[External] : Re: This expression in lambda in early construction context

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Fri Jun 7 21:34:43 UTC 2024


Hi Ella,
the problem here is that, since the lambda needs to refer to "this", 
it's as if you need to pass "this" to create the lambda object.

To make it simpler, you can think of the lambda as a local class (not 
entirely accurate, but I think it paints a good analogy for what's going 
on here):

class Main {
     int a;
     Main() {
         this.a = 1; //line A
         class Foo {
               Main this$0;
               Foo(Main this$0) { this.this$0 = this$0; }
               void run() { this$0.a = 1; }
         }
         Foo lmb = new Foo(this); // line A

         lmb.run(); //line B
         super();
     }


Like before, in line (A) we create the lambda expression (here modelled 
as a local class). Note that the local class wants a construction 
parameter, of type Main (since the local class needs to refer to it). 
But then, in line (B), we need to supply an argument of type Main, 
namely "this". So here we are effectively reading/accessing "this" 
before the super constructor has been called.

The lambda expression, being so compact, hides a bit of the problem and 
you are right that it's a bit confusing at first, but I hope the example 
above clarifies things a bit.

Cheers
Maurizio

On 05/06/2024 22:29, Ella Ananeva wrote:
>
> Thanks for pointing this out, Chen.
>
> Please bear with me for a moment. If we have a lambda as a local 
> variable in the constructor, it cannot be invoked outside of the 
> constructor, right?
>
> class Main {
> int a;
> Main() {
> this.a = 1; ///line A
> /Foo lmb = () -> this.a = 1;//
>
> //lmb.foo(); //line B
> super();
>     }
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240607/7add6563/attachment.htm>


More information about the amber-dev mailing list