Effectively final

Steven Simpson ss at comp.lancs.ac.uk
Mon Aug 15 07:08:46 PDT 2011


Hi!

On 30/07/11 10:32, Tim Fox wrote:
> On 30/07/2011 09:24, Steven Simpson wrote:
>> Finally, to translate your code:
>>
>>      void context() {
>>        class Anon {
>>          int result1, result2;
>>
>>          void callback1(Some args) {
>>            // Set result1.
>>          }
>>
>>          void callback2(Some args) {
>>            // Set result2.
>>          }
>>
>>          void complete() {
>>            sendResponse(result1 + result2);
>>          }
>>        }
>>
>>        Anon anon = new Anon();
>>        Composer.when(Services.foo(args, anon#callback1),
>>                      Services.bar(args, anon#callback2))
>>                .act(anon#complete);
>>      }
>>
>> I dare say, it's not as convenient as mutable locals, but does it meet
>> your needs without being too ugly/clunky?
> [...] Your examples works, but yes it's too clunky (for me anyway).

Slight variation:

    void context() {
      new Object() {
        int result1, result2;

        void callback1(Some args) {
          // Set result1.
        }

        void callback2(Some args) {
          // Set result2.
        }

        void complete() {
          sendResponse(result1 + result2);
        }

        {
          Composer.when(Services.foo(args, this#callback1),
                        Services.bar(args, this#callback2))
                  .act(this#complete);
        }
      };
    }


> Consider another example written in Ruby:
>
> def foo(socket)
>     timed_out = false
>     system.set_timeout(100) { timed_out = true }
>     socket.on_data{ puts "Got data" if !timed_out}
> end

Similarly:

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

The method refs can also be replaced by lambdas:

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

Cheers,

Steven


More information about the lambda-dev mailing list