kotlindelegatesdelegationkotlin-delegate

Kotlin: referring to delegate that is not passed by constructor


I want to use Kotlin delegation in a particular context.

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 construction of my Derived class with arbitrary delegates.


Solution

  • 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")
        }
    }