AlikElzin-kilaka
AlikElzin-kilaka

Reputation: 36001

How to get delegated instance in Kotlin?

I'd like to get the instance of a delegated class.

Specifically, in the following example, I'd like to get an instance of the passed Base - b but get an error when trying to use b.

interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}

open class Derived(b: Base) : Base by b {
    override fun print() {
        printSomethingBefore()
        b.print() // b isn't recognized :(
        printSomethingAfter()
    }
}

* Source for the example: https://kotlinlang.org/docs/reference/delegation.html

Upvotes: 1

Views: 123

Answers (1)

AlikElzin-kilaka
AlikElzin-kilaka

Reputation: 36001

Declaring b with the val prefix did the trick:

... Derived(val b: Base) : Base by b ...

Upvotes: 3

Related Questions