Reputation: 1009
I have migrated my application from Java to Kotlin. In Java, the copying was working just fine. However, when migrated to Kotline it was not working. After that, I came to know about copy method in Kotlin
I have tied this, but it seems I am doing something wrong.
Here is my function :
fun updateSwitchState(deviceName: String, switchNumber: Int): AuraSwitch? {
val singleDevice = Switch()
for (c in FourNodeDevice) {
if (deviceName == c.name) {
val copyDevice : SwitchClone = SwitchClone(c.state, c.name)
val state = copyDevice.copy(state = copyDevice.state)
state.updateState(switchNumber)
singleDevice.state = state.state
return singleDevice
}
}
return null
}
Whenever I change data in object state
in updateState Method the value in object c
also gets changed. Any help will be useful
Upvotes: 0
Views: 8728
Reputation: 12725
For Kotlin when using the Kotlin Data Class data class
you get a function called copy()
for you. But If your Class is not a Data Class
and your project has Gson
and you want to copy the whole object ( probably edit after getting it ), Then if all those conditions are true then this is a solution. This is also a DeepCopy. ( For a data Class you can use the function copy()
).
Then if you are using Gson
in your project. Add the function copy()
:
class YourClass () {
// Your class other stuffs here
fun copy(): YourClass { //Get another instance of YourClass with the values like this!
val json = Gson().toJson(this)
return Gson().fromJson(json, YourClass::class.java)
}
}
If you want to install Gson then get the latest version here.
Upvotes: 1
Reputation: 1009
The copy()
did not solve my purpose. However clone()
did. I added the following line in my code and it worked as I desired.
val state = c.states.clone()
Upvotes: -1
Reputation: 17268
You never create a copy of a state
object.
This call creates another SwitchClone with values identical to copyDevice
itself.
val state = copyDevice.copy(state = copyDevice.state)
copy()
only creates a shallow copy, which means all of your objects, in that case c
, copyDevice
and state
point to the same c.state
.
You need to explicitly create a deep copy (depending on what properties are mutable) of state object and assign it to copyDevice.state
field.
Upvotes: 1