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?
Copy code
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()
}
}
Vitali Plagov
07/25/2022, 7:56 AM
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
Copy code
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()
}
}