New Collections interface - Sized
Brian Goetz
brian.goetz at oracle.com
Fri Apr 23 22:07:43 UTC 2021
>> Is there a compelling example of where this would be used by clients?
> Here are some examples:
> https://stackoverflow.com/questions/10988634/java-global-isempty-method
Without passing judgment on the sort of dynamically typed programs that
need a method like this, or wondering what monstrosities such code uses
to actually _get_ the data out of this weird ad-hoc union, note that
this code becomes dramatically simpler with pattern matching:
return switch (c) {
case null -> true;
case CharSequence cs -> cs.length() == 0;
case Collection c -> c.isEmpty();
case Object[] os -> os.length == 0;
default -> { weird reflective thingy }
}
Note also that a Sized abstraction only addresses two of these five
cases -- CharSequence and Collection. The others would still require
such ad-hoc treatment.
And while it may seem like I have pattern matching on the brain, there's
a point to bringing up pattern matching -- which is that real code often
ends up dealing with ad-hoc unions, and a linguistic mechanism for
abstracting computations over ad-hoc unions is often a better solution
if you find yourself in ad-hoc land than trying to partially unify it.
But again, if you are treating these things as containers, then a Sized
doesn't get you very far, because if you conclude the thing isn't empty,
you're going to want to get stuff out, and Sized has no methods for
that. So presumably there's some companion to Sized for accessing
elements by index:
interface HasStuff<T> extends Sized {
T get(int index);
}
And note that in order for HasStuff to be useful, it has to extend
Sized, because, no intersection types. Which suggests Sized is not the
abstraction you are looking for.
And again, pattern matching:
Object getElement(Object thingWithStuff, int index) {
return switch (thingWithStuff) {
case null -> null;
case Object[] os -> os[index];
case Collection<?> c -> c.get(index);
... more if you can think of them ...
};
More information about the core-libs-dev
mailing list