https://kotlinlang.org logo
Title
v

Vitali Plagov

07/25/2022, 7:51 AM
I have a base class and two child classes extending this parent class. Can I declare a return type of the method in the parent class so that it will return the type of the child class that is extending it?
open class Parent {
  fun load() {
    return ... // don't know what to return here
  }
}

class ChildA : Parent () {
  fun methodA() = ...
}

class ChildB : Parent () {
  fun methodB() = ...
}

class Usage {
  fun fooA() {
    ChildA().load().methodA() // I want to achieve this chaining
  }

  fun fooA() {
    ChildB().load().methodB()
  }
}
I.e., I want to reuse
load()
method from parent for both childs, but then continue with child’s members and methods
d

dmitriy.novozhilov

07/25/2022, 9:20 AM
abstract class Parent<T : Parent<T>> {
    abstract fun load(): T
}

class ChildA : Parent<ChildA> () {
    override fun load(): ChildA = TODO()

    fun methodA(): Int = TODO()
}

class ChildB : Parent<ChildB> () {
    override fun load(): ChildB = TODO()

    fun methodB(): Int = TODO()
}

class Usage {
    fun fooA() {
        ChildA().load().methodA()
    }

    fun fooB() {
        ChildB().load().methodB()
    }
}