Kulwinder Singh Rahal
Kulwinder Singh Rahal

Reputation: 519

kotlin,How value of Actual variable we can change in another class to which it passed using parameter?

I am using Delegation in Kotlin. So therefore I have base class which handles common network result but only difference is Data(Model class)

class BaseDataDelegation<T>(var oldData: T): WebDataListener<T> {
    override fun onSuccess(data: T) {
        oldData = data //oldData's original variable value which is inside main activity should also be updated

               /.../
    }

    override fun onFailed() {
      /.../
    }


}

then In MainActivity I'm calling

dataManager.getResponse(BaseDataDelegation(oldData))//in DataManager.getResponse(listener:WebDataListener<T>)  

Now as I passed oldData to BaseDataDelegation, so when value of oldData is changed in BaseDataDelegation class it should reflect back to variable of MainActivty.
How can I do this in Kotlin?

Upvotes: 2

Views: 1318

Answers (1)

hotkey
hotkey

Reputation: 147951

You can use a mutable property reference to achieve this. Here's an example:

class BaseDelegation<T>(val property: KMutableProperty0<T>) {
    override fun onSuccess(data: T) {
        property.set(data)
    }
}

Then, to construct a BaseDelegation, use a bound reference to a property, e.g. this::oldData or myActivity::oldData (the property itself should be mutable, i.e. var).

Here's a simplified runnable demo: (link)

Upvotes: 4

Related Questions