Home > OS >  How can i specify that the type parameters of a class have to inherit the class itself? ( class A<
How can i specify that the type parameters of a class have to inherit the class itself? ( class A<

Time:08-20

i have an abstract class with a type parameter:

abstract class AClass<T>(){ ___ }

however, i want to specify that the type T must be a child of AClass itself.

abstract class AClass<T : AClass>(){ ___ }

this doesnt work. I also tried:

abstract class AClass<T : AClass<*>>(){ ___ }

but the IDE gives me a "Finite Bound Restriction" Error.

Is it even possible to achieve the desired behaviour in Kotlin?

CodePudding user response:

Even though some other languages support this self type param, This is not possible in kotlin. Because it may lead to recursive generics. Kotlin team reported that implementation of this feature is difficult in accomodate with kotlin design. Also it feels too noisy to have self types.

Useful Links:

https://youtrack.jetbrains.com/issue/KT-6494#comment=27-882961

https://discuss.kotlinlang.org/t/self-types/371/86

https://discuss.kotlinlang.org/t/this-type/1421/10

  • Related