Search code examples
kotlininheritancetype-parameter

How can i specify that the type parameters of a class have to inherit the class itself? ( class A<T : A>{ __ } ) | Kotlin


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 doesn't 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?


Solution

  • 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