Specialized methods for a generic class based on type argument

Tagir Valeev amaembo at gmail.com
Mon May 9 07:24:58 UTC 2022


Your sample would not work anyway, as you cannot apply `+=` to any
number. It's applicable to primitive types only known at compilation
time.

This could be useful for stream.sorted() (which de-facto works only
for streams having comparable elements).
Syntactically (bikeshedding, yeah!), we might adapt the receiver
parameter for this purpose, allowing to specify potentially
convertible type there:

interface Stream<T> {
  Stream<T> sorted(Stream<? extends Comparable<?>> this);
}

So the method call is allowed only when the specified receiver type is
assignable from the actual receiver type.

Such a change would require encoding in class files. If I understand
correctly, currently there's no good place where this information
could be recorded. So probably a new attribute will be required in
class files, which requires changes in JVM specification. Also,
changes in reflection API to support retrieving this information
reflectively. Also, changes in javax.model API to support annotation
processors. Quite a lot of work for a feature with limited usefulness.

A typical work-around in current Java is to use a static method for
this purpose.

With best regards,
Tagir Valeev

On Mon, May 9, 2022 at 7:45 AM Swaranga Sarma <sarma.swaranga at gmail.com> 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