Reputation: 1915
Say I have open class C(val c:C)
and I want to subclass it as class D():C(this)
This is invalid according to the compiler because 'this' is not defined in this context
Is there a way to get this to do what I want? Specifically, I'd like for D
to have a constructor that can be called without any arguments and will pass the D
object being constructed to C
's constructor. In my case, it's fine that this object may not be fully constructed yet.
I'm open to any solutions that don't involve changing C
, reflection included.
Upvotes: 1
Views: 68
Reputation: 147981
There's no straightforward solution, because it does not seem to be a good idea.
The constructor of the super class gets executed before the constructor of the class itself does (more details here). Thus passing this
instance that has not been initialized at all to the super constructor in place of a valid instance may break some of the logic of the super constructor (e.g. it may expect the c
's properties to have some meaningful values, but they don't).
If you need this so bad, you can try to create an instance of D
first with some fake/default C
, then create another D
with the first one:
class D(c: C) : C(c)
fun createD(defaultC: C): D {
val firstD = D(defaultC)
return D(firstD)
}
Though this definitely does not cover all possible use cases.
Upvotes: 2