Multiple SAMs for same concept
Stephen Colebourne
scolebourne at joda.org
Thu Jul 15 16:34:17 PDT 2010
One problem noted with the removal of function types is that multiple
SAMs with the same signature are not compatible. For example:
http://gee.cs.oswego.edu/dl/jsr166/dist/extra166ydocs/extra166y/Ops.Generator.html
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Supplier.html
http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Provider.html
Having these different incompatible definitions is problematic, for
example when the developer has created a library of reusable
implementations implementing one SAM, and then wants to use them using
another (eg. a newly added JDK SAM).
Given the method:
private void process(Generator<String> gen) { ... }
the most recent draft SotL would allow the following two choices for conversion:
Supplier<String> supplier = ...
process( {-> supplier.supply()} ); // manual conversion to a Generator
process( supplier#supply() ); // using method ref to manually
convert to Generator
While the two solutions are not terrible, they are less than ideal. I
would argue that the ideal would be:
process(supplier); // auto-boxed from Supplier to Generator
Auto-boxing is of course very tricky, as it is in method resolution.
I'm not going to start to write rules to define how it should work.
One compromise option I came up with was:
process( supplier# );
Here, the caller syntax means that the compiler should infer the
method name of the method reference on the basis that it is a SAM.
This reduces verbosity, is a simple rule, and allows for easier
conversion between the myriad of different SAMs that represent the
same thing.
Alhough P.Lambda could just duck this issue, I fear that doing so
would be a mistake. There are lots of SAMs out there already, and just
adding a standard set to JDK 7 doesn't solve this particular
"backwards compatibility" issue.
Stephen
More information about the lambda-dev
mailing list