Also I should note that this is not binary compatible since map/filter and
other intermediate operations will need to return a CacheStream instead of
a Stream as they do currently. This is to make sure the terminal operator
when invoked is done upon the CacheStream which defines the Serializable
interfaces.
This however would be used with [1], which is targeted for 7.2, to allow
for much easier way to provide Callable/Runnable instances through lambdas
without having to do the ugly casting.
[1]
https://issues.jboss.org/browse/ISPN-6074
On Tue, Feb 9, 2016 at 11:36 AM William Burns <mudokonman(a)gmail.com> wrote:
I wanted to propose a pretty simple way of making the lambdas
serializable
by default that I stumbled upon while working on another issue.
I noticed that in the method resolution of the compiler it does some nice
things [1]. To be more specific when you have 2 methods with the same name
but vary by argument types, it will attempt to pick the most "specific"
one. Specific in this case you can think of if I can cast one argument
type to the other but it can't be cast to this type, then this one is most
specific.
Here is an example, given the following class
interface SerializableFunction<T, R> extends Serializable, Function<T, R>
The stream interface already defines:
Stream map(Function<? super T, ? extends R> mapper);
But we could add this to the CacheStream interface
CacheStream map(SerializableFunction<? super T, ? extends R> mapper);
In this case you have 2 different map methods accessible from your
CacheStream instance. When passing a lambda the Java compiler will
automatically choose the most specific one (in this case the
SerializableFunction one since Function can't be cast to
SerializableFunction). This will then make the lambda automatically
Serializable. In this way nothing special has to be done (ie. explicit
cast) to make the instance Serializable.
This allows anyone using our Cache interface to immediately get lambdas
that are Serializable when using Streams.
The main problem however would be ambiguity because the Serialization
would only be applied assuming you are using a defined class of CacheStream
etc. Also this means there are 2 methods (but that seems fine to me), so
it could cause a bit of confusion. The non serialization method is still
helpful if people want to their own Externalizer, since their
implementation doesn't have to implement Serializable then.
What do you guys think? It seems like a decent compromise to me.
- Will
[1]
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5