0

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

Aarth Tandel
  • 1,001
  • 12
  • 32

3 Answers3

1

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.

Pawel
  • 15,548
  • 3
  • 36
  • 36
  • Ohh I see, I thought the same as my value in object C was also changing. Any idea how can I make a deep copy of object in kotlin? – Aarth Tandel Jun 18 '18 at 12:08
1

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.

Xenolion
  • 12,035
  • 7
  • 33
  • 48
-1

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()
Aarth Tandel
  • 1,001
  • 12
  • 32