generics - Java API class having a method with a meaningless type wildcard -
in java 8, class java.util.optional (javadoc) class offers functionality of "maybe" monad or option type.
more directly:
public final class java.util.optional<t> extends object
a container object may or may not contain non-null value. if value present, ispresent() return true , get() return value.
one of methods is:
<u> optional<u> map(function<? super t,? extends u> mapper)
if value present, apply provided mapping function it, , if result non-null, return optional describing result.
the question why map() use type wildcard on u type.
my understanding of type wildcarding that:
? super t designates type set of classes given subclassing path object t (both object , t included) union set of interfaces found on subinterfacing path pulled in "as sidedish" via implements.
and ? extends u designates type set of classes extend u (uincluded).
so 1 write:
<u> optional<u> map(function<? super t,u> mapper)
without loss of information.
or not?
not quite.
a function<? super t, u> not same function<? super t, ? extends u>.
for example, still optional<charsequence>, if passed function<object, string> method. if method defined <u> optional<u> map(function<? super t, u> mapper), not possible.
that because generics invariant: <t> not same <? extends t>. that's design decision implemented in java language.
let's see how jon skeet explains happen if generics not invariant:
class animal { } class dog extends animal { } class cat extends animal { } public void ouch() { list<dog> dogs = arrays.aslist(new dog(), new dog()); list<animal> animals; // legal, right? because list of dogs list of animals. list<animal> animals = dogs; // legal, right? because cat added // list of animals, because cat animal. animals.add(new cat()); // unfortunately, have confused cat. } although i'm not entirely sure mean in comments, i'll try elaborate.
if have full control on function provide, doesn't matter whether method's signature function<? super t, u> or function<? super t, ? extends u>, you'll adapt function accordingly. authors of method wanted method as flexible possible, allowing 1 provide function second parameter subclass of u, instead of u itself. widen lower bound u subtype of u.
so function should read
<u> optional<? the-most-general-but-fixed-supertype-of u> map(function<? super t, u> mapper)expressing way awkward.
i indeed awkward. in addition, there difference between proposed notation , actual method signature of map(), involve implications of lower bounds , upper bounds.
read more:

Comments
Post a Comment