Need curiously reucurring template pattern in Kotlin?


#1

Is there a better way of solving the follow problem than with the curiously recurring template pattern in Kotlin?
(https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)

Example:

fun main(args: Array<String>) {
    val ok: Derived = Derived().returnsDerived()
    val fails: Derived = Derived().alsoUsesDerived() // This will be of type Base instead
}
interface Base {
    fun returnsDerived(): Base
    fun alsoUsesDerived() = returnsDerived()
}
class Derived : Base {
    override fun returnsDerived() = this
}

Fixed version:

fun main(args: Array<String>) {
    val ok: Derived = Derived().returnsDerived()
    val fixed: Derived = Derived().alsoUsesDerived() // Now it will be type Derived
}
interface Base<T : Base<T>> {
    fun returnsDerived(): T
    fun alsoUsesDerived() = returnsDerived()
}
class Derived : Base<Derived> {
    override fun returnsDerived() = this
}