Specialized methods for a generic class based on type argument

Swaranga Sarma sarma.swaranga at gmail.com
Mon May 9 05:44:34 UTC 2022


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