Fwd: Closures: converting closures returning void, and interfaces vs. one-abstract-method abstract classes

Neal Gafter neal at gafter.com
Sun May 11 20:20:16 PDT 2008

---------- Forwarded message ----------
From: Paul Holser <pholser at gmail.com>
Date: Sun, May 11, 2008 at 2:54 PM
Subject: Closures: converting closures returning void, and interfaces vs.
one-abstract-method abstract classes
To: neal at javac.info

Hi Neal,

I enjoyed your "Closures Cookbook" talk at JavaOne.  I've started
experimenting with the BGGA prototype (dated 2008-04-27), and had a
couple of questions.  I have an existing Java library that uses
"function types", and wanted to see whether closure conversion would
work with it "out of the box", so to speak.

Attached are source for a Range class, a UnaryFunction interface, and
a Main that uses both.

1) When the signature of Range#forEachDo is:

   void forEachDo( UnaryFunction<? super Integer, ?> operation )

Main fails compilation with:

 Main.java:3: forEachDo(UnaryFunction<java.lang.Integer,?>) in Range
cannot be applied to ({int => void})
       Range.fromTo( 1, 4 ).forEachDo( System.out#println(int) );
1 error

When I change the signature to:

   <R> void forEachDo( UnaryFunction<? super Integer, ? extends R> operation

Main compiles and runs fine.

What is it about the second signature that allows a void-return-type
closure in as a parameter to forEachDo(), whereas such a closure is
denied entry to the method with the first signature?

The good news is that I can change the signature of forEachDo to the
second version, and my test code, etc. compiles fine.

2) Would you elaborate a bit on some of the technical reasons why an
abstract class with one abstract method cannot be the target type of a
closure conversion?  In other words, why would the following
definition of UnaryFunction not allow closure conversion:

   abstract class UnaryFunction<A, R> {
       abstract R evaluate( A argument );

       final <T> UnaryFunction<T, R> compose( UnaryFunction<? super
T, A> other ) {
           // composition...

       // ... other concrete methods...

Thanks for your time and great work!


"To only a fraction of the human race does God give the privilege of
earning one's bread doing what one would have gladly pursued free, for
passion. I am very thankful."
-- Fred Brooks, "The Mythical Man-Month"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.openjdk.java.net/pipermail/closures-dev/attachments/20080511/785b0659/attachment.html 

More information about the closures-dev mailing list