Lambda weird scoping rule

Remi Forax forax at univ-mlv.fr
Tue Feb 5 13:46:42 PST 2013


Hi guys,
we said a long time ago that we may re-visit the very specific rule that 
doesn't allow
to use a variable which is already in the outer scope.
I've been bitten by this rule too often to consider that this rule worth 
the trouble.

We should keep things simple.

Here is the latest example.

public class LambdaChainTest {
   interface Completer<V, A> extends CompletionHandler<V, A> {
     public void completed(V result, Throwable exception, A attachment);

     @Override
     public default void completed(V result, A attachment) {
       completed(result, null, attachment);
     }

     @Override
     public default void failed(Throwable exc, A attachment) {
       completed(null, exc, attachment);
     }

     public default Completer<V, A> onError(Consumer<? super Throwable> 
consumer) {
       return (result, exception, attachment) -> {
         if (exception != null) {
           consumer.accept(exception);
           return;
         }
         completed(result, exception, attachment);
       };
     }
   }

   public static void main(String[] args) throws IOException {
     ByteBuffer buffer = ByteBuffer.allocate(8192);
     AsynchronousFileChannel channel = 
AsynchronousFileChannel.open(Paths.get("foo.txt"));
     channel.read(buffer, 0, buffer, ((Completer<Integer, ByteBuffer>) 
(result, exception, buffer) -> {
       buffer.flip();
       System.out.println(new String(buffer.array(), 
Charset.defaultCharset()));
     }).onError(e -> e.printStackTrace()));
   }
}

Rémi



More information about the lambda-spec-experts mailing list