fweigl
fweigl

Reputation: 22038

Kotlin type parameter subclass of

When I have this class:

abstract class MyAbstractClass<T> {
   abstract fun convert() : T
}

Can I somehow specify that T should be a subclass of MyAbstractClass?

Edit: abstract class MyAbstractClass<T : MyAbstractClass> does not work, because the MyAbstractClass in <T : MyAbstractClass> would require the type parameter again.

Upvotes: 1

Views: 1298

Answers (2)

FilipRistic
FilipRistic

Reputation: 2821

You could do it with following approach:

abstract class MyAbstractClass<out T : MyAbstractClass<T>> {
    abstract fun convert() : T
}

class ConcreteClass<T>(val str : String) : MyAbstractClass<ConcreteClass<T>>(){
    override fun convert(): ConcreteClass<T> = this
}

fun main(args: Array<String>) {

    val instance: MyAbstractClass<ConcreteClass<String>> = ConcreteClass("str")
    val converted: ConcreteClass<String> = instance.convert()
}

Upvotes: 1

anber
anber

Reputation: 3655

Maybe something like this one:

abstract class MyAbstractClass<T : MyAbstractClass<T>> {
    abstract fun convert(): T
}

Upvotes: 1

Related Questions