ArrayFactory SAM type / toArray
Brian Goetz
brian.goetz at oracle.com
Wed Sep 19 13:39:29 PDT 2012
In looking at the Collection API, there are two forms of toArray method,
both of which are unfortunate:
Object[] toArray() -- returns an Object[], not a T[]
T[] toArray(T[]) -- reflective instantiation
Lambdas offer us a way out of this:
interface ArrayFactory<T> {
T[] make(int n);
}
interface Collection<T> {
T[] toArray(ArrayFactory<T> factory) default {
return toArray(factory.make(size());
}
}
The default is imperfect (though no worse than what clients typically
do), and concrete implementations of Collection can do better.
Given that Stream has a toArray method, my preference would be to expose
T[] toArray(ArrayFactory<T>)
possibly as the only toArray method.
We might be able to extend the constructor reference syntax to arrays:
Foo[]::new. If not, n -> new Foo[n] works fine.
More information about the lambda-libs-spec-observers
mailing list