Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin: referring to delegate that is not passed by constructor

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 call super.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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>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")
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading