https://kotlinlang.org logo
Title
k

Kevin

12/26/2018, 1:51 AM
I have an abstract parent class A and child classes B and C. I want to declare an abstract method in A such that the implementation in B and C must have a return type of B or C respectively. Is there a way to do this?
s

Shawn

12/26/2018, 1:52 AM
sounds like you want self types
and on the JVM that means bootleg self types vis-a-vis the curiously recurring template pattern
u

ursus

12/26/2018, 2:57 PM
generics, or, override the function and narrow the type
v

Vincent ETIENNE

12/26/2018, 4:32 PM
Maybe use the Sealed Class and in A use when() with type ?
u

ursus

12/26/2018, 5:43 PM
how will you change the return type with that
m

mcbeelen

01/02/2019, 9:19 AM
I used generics to accomplish that behaviour
abstract class AbstractParentClass<T> where T : AbstractParentClass<T>  {
    abstract fun yield() : T
}

class ActualB : AbstractParentClass<ActualB>() {
    override fun yield() = ActualB()
}

class ActualC : AbstractParentClass<ActualC>() {
    override fun yield() = ActualC()
}