Specialized methods for a generic class based on type argument
Brian Goetz
brian.goetz at oracle.com
Mon May 9 13:51:57 UTC 2022
What you are suggesting is what we call a _conditional method_; a method
that is a member of some parameterizations but not others. This is an
entirely reasonable concept, and we've given extensive thought to the
topic under Project Valhalla, but there are a number of challenges that
mean such things are at least a few steps away:
- It is not merely enough to say that sum() is only a member of
List<T> for certain T; as your example shows, you would like to be able
to get at the zero value for T, and its addition function. (More
specifically, sum() works when T is a *monoid*, and the implementation
of sum() requires access to a *witness* to it's monoid-hood.)
- Said witnessing requires some degree of runtime reification, either
in the form of direct reification of generic type parameters (as C#
does), or the use of implicit arguments (as Scala does.)
- As your example suggests, even if you had the above, you probably
would soon be wondering/asking/complaining "why can't I say `+`, rather
than calling `add`", so in addition to asking for reified generics and
witnesses to type classes, you are also asking for operator overloading.
None of the above are out of the question, but each are obviously a
significant lift, so don't expect it to fall out as an "Amber-sized"
feature. More like "Add generics to Java".
On 5/9/2022 1:44 AM, Swaranga Sarma wrote:
> Apologies if this is not the right mailing list; I did not find a dedicated
> mailing list for generics and Amber deals with language level improvements
> hence posting it here.
>
> I want to be able to write specialized methods based on the type argument
> for my generic class. Using the List interface as an example:
>
> interface List<T> {
> _if_T_instanceof_Number Number sum() {
> T sum = 0;
> for (T t : this) {
> sum += t;
> }
> return sum;
> }
> }
>
> The above method can be called only if the list instance is of type List<?
> extends Number> and if the reference type is of raw type then these methods
> should not be visible at the call site. There are other compatibility
> concerns like what if a subinterface or an implementing class defines these
> methods but I am of course leaving these to the experts to deal with. ;-)
>
> Is this something that might be possible in the future?
>
> Regards
> Swaranga
More information about the amber-dev
mailing list