Kotlin: referring to delegate that is not passed by constructor
Asked Answered
M

2

8

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.

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.

Meijer answered 21/4, 2022 at 13:18 Comment(0)
W
7

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")
    }
}
Wawro answered 21/4, 2022 at 13:24 Comment(0)
F
0

If you don't need a reference to the delegate, you can also say simply,

class Derived : Base by BaseImpl(42)
Fibrin answered 12/10, 2022 at 2:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.