Home > Software design >  Referring the class that extends this class in a function
Referring the class that extends this class in a function

Time:11-10

https://pl.kotl.in/WJxo0DujU (below is the code in the link)

open class A() { }

class B(): A() { 
   fun pew2() { }
}

fun <a: A> a.pew() = apply { }

fun main() {
    val b = B()
    b.pew().pew2()
}

Is there a way to have the function pew() in class A (not in A's companion object) and still be able to type b.pew().pew2() (not b.apply { pew().pew2() })?

CodePudding user response:

You could create the pew() method in A and have the method return the instance itself:

open class A() { 
    fun pew() = this 
}

class B(): A() {
    fun pew2() { }
}

fun main() {
    val b = (B().pew() as B).pew2()
}

CodePudding user response:

You can override the function in B and narrow the return type.

open class A() { 
    open fun pew(): A {
        //...
        return this
    }
}

class B: A() { 
    fun pew2() { } 
    override fun pew(): B {
        super.pew()
        return this
    }
}

Kotlin doesn't have a self type that would make these kinds of chainable functions easier to implement, but the apply function makes chainable functions that return the same object unnecessary.

  • Related