jeudi 23 juin 2022

Java generics, constraining the type to the 'self' type

This is a rather specialized question and I doubt there is a solution.

I've got a type hierarchy like A {}, B extends A{}, C extends A {}. A defines an abstract method <T extends A> T scale(double v).

The problem is that T is not anchored and you can assign the result to any type.

The solved this problem in enum (and that is why I think there is no solution) by declaring the 'self' type as a generic parameter:

 class A<T extends A<T>> { T scale(double v) { ... ;} }
 class B extends A<B> {}
 class C extends A<C> {}

Another solution would be to write the scale method in each subclass:

 class A<T extends A<T>> { A scale(double v){...} }
 class B extends A<B> { B scale(double v) { super.scale(v);}}
 class C extends A<C> { C scale( double v) { super.scale(v);} }

However, this is all ugly and lots of work.

I do not see why the compiler could not solve this problem. (I am probably missing something.) What I would like is something like this:

 class A { this scale(double v); }

Now this clearly does not work but I wonder if people found interesting generic hacks to constrain a generic return type or a generic parameter to the 'current' type the compiler observes.





Aucun commentaire:

Enregistrer un commentaire