Allow creating generic subtype functions on a parent class

Example usecase:

fun <T : SomeClass> T.someFunc(...): OtherClass<T> {
    return OtherClass<T>(...)
}

This way:

class X(...) : SomeClass(...)
myX = X()
myX.someFunc(...)  // return type: OtherClass<X>

Right now I have to define this function outside of the SomeClass class definition, but there should be a way for kotlin to support this.
The alternative I’m using right now is

class SomeClass {
    // ...
    fun someFunc(...): OtherClass<SomeClass> {
        return OtherClass<SomeClass>(...)
    }
}

This way:

class X(...) : SomeClass(...)
myX = X()
myX.someFunc(...)  // return type: OtherClass<SomeClass>

which, while similar, doesn’t give the results I want, as it returns OtherClass<SomeClass> at all times even when called from a subclass.

1 Like

Unfortunately this is not supported properly, it would need what is generally called a self-type. Kotlin doesn’t have it mainly because the JVM doesn’t have it. Remember however that your child types can return the more specific type (and be declared to do so) even if it is not possible otherwise. Make sure to specify variance though: OtherClass<out SomeClass>.

1 Like