Andrey Epifantsev
Andrey Epifantsev

Reputation: 1104

Kotlin: how to pass a property of a data member to an own property?

There are two classes. The first class has a public property. The second class has a private data member that is an instance of the first class and a public property:

class A {
    var s = "test"
}

class B {
    private var a = A ()
    public val prop = a.s
}

I would like the prop to be a reference to a.s property. If we read prop, we get the value stored in a.s. And if we write to prop, then the new value is stored in a.s. If the contents of a.s change somewhere else, then prop should also update accordingly. Can this be done in a simple way? I tried to do, as in this code, public val prop = a.s, but this does not work - there is no connection between the properties.

Is there an easy way in Kotlin to make such a reference to a property of another class?

Upvotes: 0

Views: 330

Answers (1)

Animesh Sahu
Animesh Sahu

Reputation: 8096

There is no connection between the properties

Well they both are referencing to the same String object in the heap memory, they both are exactly the same.

But if you override the reference of the A.s to another String object, then A.s is holding a new reference and B.prop is holding the old reference

So how to solve this?

You can simply delegate the getter of B.prop to A.s in Kotlin.

class A {
    var s = "test"
}

class B {
    private var a = A ()
    val prop: String
        get() = a.s
}

Upvotes: 2

Related Questions