Problem of defender methods with generic methods
Peter Levart
peter.levart at marand.si
Mon Nov 15 23:35:01 PST 2010
On 11/15/10, Alex Buckley wrote:
> Hi Ali,
>
> On 11/15/2010 2:51 AM, Ali Ebrahimi wrote:
> > if compiler can accept the following syntax:
> >
> > <A extends T & Comparable<? super A>> extension A max() default
> > Trait.<A>max;
> >
> > The aim is here to restrict calling of max only on CustomizedLists of
> > Comparables, otherwise compiler raise compile time error.
> >
> > I know this is a new concept- a kind of conditional inheritance. but
> > currently this can not be implemented in java, unless by introducing a new
> > subinterface. then we have two interfaces.
>
> You and Steven have identified a valuable idiom that avoids new subtypes
> - we can call it "conditional inheritance" if you like - but
> unfortunately the generics mechanism cannot express it. Namely, the
> bound of a type variable can be _either_ another type variable _or_ a
> combination of classes and interfaces. (See JLS3 4.4.)
>
> The trouble is erasure: if a type variable's bound could be 'T &
> Comparable<...>', then it would not be clear whether to erase max's
> return type to Object (the erasure of T) or Comparable (the erasure of
> Comparable<...>). I guess we could pick the former, but the Signature
> attribute would want to record both T and Comparable<..> for later
> typechecking of A's witness from the call site. (Does it subtype List's
> type argument _and_ Comparable<..> ?)
>
> JLS3 4.4 arranged things to ensure a unique erasure, so it's not just a
> matter of relaxing syntax to allow your desired type variable for max.
>
> I personally believe we will want to add extension methods that further
> restrict the enclosing generic type's bounds, and that a new
> subinterface (ComparableList<T extends...>) will often be undesirable.
> But more experience is needed.
>
> Alex
Why are extension methods so special? Wouldn't also other kinds of methods and class constructors benefit from such a feature? Take for example the interface SortedSet and one of it's implementations: TreeSet. It would be desirable that constructors not taking a Comparator restrict type variable to a subtype of Comparable.
Regards, Peter
>
>
More information about the lambda-dev
mailing list