Updated State of the Lambda
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Tue Oct 19 01:22:15 PDT 2010
Hi Gernot,
On 19/10/10 08:02, Gernot Neppert wrote:
> 2010/10/18 Reinier Zwitserloot<reinier at zwitserloot.com>:
>
>> Entirely separate from the discussion around implementation details, having
>> practices. I'm speaking specifically of using "this" as an object reference,
>> and not the "this.x" syntax to clarify which field / method you're referring
>> to. Those are scoped in reverse (If the SAM type has a field named "foo" and
>> the outer also does, then an unqualified "foo" reference will refer to the
>> SAM type's). Therefore, using Outer.this syntax will not be necessary; its
>> only for clarification: "x" refers to lambda's x, and "this.x" refers to
>> outer's X. You'd only need it when writing a lambda that is itself in an
>> inner class.
>>
>>
> Hmm, but here it gets messy, doesn't it?
> One argument in favour of 'this referring to the enclosing instance'
> is that lambdas should deliberately not resemble inner classes because
> they should stand out as a new concept (at least in Java).
>
> Unfortunately, though, lambdas *are* still instances of classes, and
> simply trying to hide that fact causes inconsistencies that should be
> at least be addressed.
>
> Consider the following TimerTask that will cancel itself conditionally:
>
> class MyClass
> {
> private final void Timer timer = new Timer();
> public void cancel()
> {
> timer.cancel();
> }
>
> public void scheduleHelloWorld()
> {
> timer.scheduler( #{
> System.out.println("Hello world");
> if(new Random().nextBoolean()) cancel();
> } , 1000, 1000 );
> }
> }
>
> Merely prefixing 'cancel' with 'this' will now cause the TimerTask to
> cancel the entire timer instead:
>
not quite, this.cancel() and cancel() [unqualified] both refers to
MyClass.cancel - in the latter case the reference to the 'right' this
will simply be inferred by the compiler, as already happens with Java.
But, from the compiler perspective, there's no TimerTask.cancel()
available inside the lambda body - in order to call that you should use
the DA/DU trick discussed yesterday:
TimerTask t = #{ ... t.cancel(); ... }
Maurizio
>
> public void scheduleHelloWorld()
> {
> timer.scheduler( #{
> System.out.println("Hello world");
> if(new Random().nextBoolean())
> this.cancel();
> } , 1000, 1000 );
> }
>
>
> Basically the meaning of 'prefixing a variable with this' has been
> reversed compared to the 'normal case' of inner classes.
> Quite counterintuitive, I think!
>
>
More information about the lambda-dev
mailing list