recursive lambda as a local variable

Zhong Yu zhong.j.yu at gmail.com
Wed Sep 11 11:11:50 PDT 2013


On Wed, Sep 11, 2013 at 12:36 PM, Dan Smith <daniel.smith at oracle.com> wrote:
> I'm pretty sure that's just the way things work.

> Fields can refer to themselves in their initializers;

This part is kind of messy, for example

public class Tmp
{
    int x = x + 1; // fail. good.

    int y = this.y +1;  // ok! allowed by JLS#8.3.2.3. probably spec bug.

    final int z;

    Tmp()
    {
        z = this.z+1; // ok! but forbid by JLS#16. probably javac bug
    }
}

With lambda it is more confusing

public class Tmp
{
    Runnable r1 = ()->r1.run(); // ok

    Runnable r2 = this.r2::run; // compiles... but
NullPointerException at runtime
}

Zhong Yu




> local variables cannot.  (This is because fields always have a value (possibly null), while local variables can't be accessed before initialization.)
>
> You could try the same thing with an int:
>
> int i = i+1;
>
> —Dan
>
> On Sep 11, 2013, at 10:37 AM, Zhong Yu <zhong.j.yu at gmail.com> wrote:
>
>> This compiles: (b106)
>>
>>    class Test
>>    {
>>        Runnable r = ()->r.run();
>>    }
>>
>> but this doesn't:
>>
>>    void test()
>>    {
>>        Runnable r = ()->r.run();
>>    }
>>
>> is that intentional or a bug?
>>
>> Zhong Yu
>>
>


More information about the lambda-dev mailing list