SAM Classes
Joshua Bloch
jjb at google.com
Thu Jan 28 17:25:55 PST 2010
Several people have pointed out rough edges in the first draft's approach to
SAM types. Some have suggested that we simply disallow lambda conversions to
SAM classes. I believe it would be wrong to give up without a fight. Here's
why:
From: Alex Blewitt <alex.blewitt at gmail.com>
Date: Wed, Dec 16, 2009 at 1:06 AM
Subject: Re: SAM types and functions
To: lambda-dev at openjdk.java.net
>
> On Thu, Dec 10, 2009 at 10:38 PM, Alex Blewitt <alex.blewitt at gmail.com>
> wrote:
>> Many existing Java libraries define interfaces which declare just one
>> method
>> or abstract classes which declare just one abstract method (so-called
>> “SAM” types).
>> A function of appropriate type is converted to an anonymous instance ...
> I'm not sure this is needed in the general case ...
> I did a scan of the Java class libraries (those with java.* or
javax.*) - there's 100 interfaces and 220 classes which fall into this
definition. Quite a lot more than I expected :-) And I can see where
this would be useful, provided that we can deal with the ambiguous
cases (e.g. as proposed earlier, with an explicit cast).
> Alex
If we're providing a nice new syntax for function objects, we should make it
usable with as many existing function-object consumers as possible. It may
not be possible to make it work for SAM-class instance consumers, but we
shouldn't give up without a fight.
Stephen Colebourne said this:
I'm guessing that SAM classes are motivated by some specific use cases,
> perhaps in the JDK. I'd strongly suggest that those use cases should have
> API changes in parallel to lambdas instead of permitting SAM classes.
This doesn't work for two reasons: It's not just the JDK, but the whole
universe of Java libraries that would have to be changed. That won't happen
overnight. Second, there were (sometimes) good reasons that interfaces were
used in preference to classes. In the the case of TimerTask, the reason was
performance: a hidden field is stashed in each TimerTask, without the need
for an extra object to incorporate the TimerTask and the hidden field. In
addition to object allocations, this saves on indirections.
I think we really must try to come up with something that works for SAM
classes. If we fail, we fail, but we have to try.
Josh
P.S. "Problems worthy of attack, prove their worth by fighting back." --
Piet Hein
More information about the lambda-dev
mailing list