I want to use Kotlin delegation in a particular context.
- The delegate should not be passed in the constructor.
- I want to keep a reference to the delegate for later use in the code. From within the method that I override, say
printMessage()
, I still need to call the delegate the same way you'd callsuper.printMessage()
in polymorphic inheritance.
I can do the first by simply instantiating an anonymous delegate in the by
clause (class Derived() : Base by BaseImpl(42)
using Kotlin's documentation example). However,
this prevents me from accessing the anonymous delegate, as there is no way that I know to reference it.
I want to do something similar to the following. The following however doesn't compile with error 'this' is not defined in this context
.
class Derived() : Base by this.b {
val b: Base = BaseImpl(42)
override fun printMessage() {
b.printMessage()
print("abc")
}
}
I do need a separate delegate for each instance of my Derived
class. So moving b
as a global variable is not an option for me.
The closest I got to what I need is with an optional parameter to the constructor. This is not a good option neither, as I don't want to allow the constructor of my Derived
class with arbitrary delegates.
CodePudding user response:
You can do this using a private primary constructor and a public secondary constructor:
class Derived private constructor(val b: Base) : Base by b {
constructor(): this(BaseImpl(42))
override fun printMessage() {
b.printMessage()
print("abc")
}
}