Effectively final

Steven Simpson ss at comp.lancs.ac.uk
Wed Sep 14 04:10:42 PDT 2011


Just a loose end...

On 15/08/11 15:41, Tim Fox wrote:
> On 15/08/2011 15:22, Steven Simpson wrote:
>>       void foo(final Socket socket) {
>>         new Runnable() {
>>           boolean timedOut;
>>           public void run() {
>>             system.setTimeout(100, #{ timedOut = true; });
>>             socket.onData(#{ if (!timedOut) System.out.println("Got data"); });
>>           }
>>         }.run();
>>       }
> Steven, firstly thanks for putting in the effort to look at this. And
> kudos for your ingenuity :)

And yet I missed this trick!:

   void foo(final Socket socket) {
     new Object() {
       boolean timedOut;
       void run() {
         system.setTimeout(100, () ->  { timedOut = true; });
         socket.onData(() ->  { if (!timedOut) System.out.println("Got data"); });
       }
     }.run();
   }

So the object doesn't have to be Runnable, and run() doesn't have to be 
public, return void, or be called run!  That's more convenient if you 
want to return a value, rather than doing tricks with Callable:

   return new Object() {
     int run() { return 0; }
   }.run();

Cheers,

Steven


More information about the lambda-dev mailing list