0

I am doing the following in Kotlin where desiredJsonStructure is a JSON structure that I define in the start of the class initialization

private lateinit var desiredJsonStructure: JSONObject

try {
    val state = JSONObject()
    state.put("xyz", JSONObject())

    desiredJsonStructure = JSONObject()
    desiredJsonStructure.put("abc", state)

} catch (e: JSONException) {
        e.printStackTrace()
}

But when I assign the desiredJsonStructure object to another object and do changes in the finalDesiredState object, same changes are reflected in the desiredJsonStructure when I try to reuse it, means it than have the value that I have assign to finalDesiredState, looks like finalDesiredState is pointing to same memory as of desiredJsonStructure, how can I create a new finalDesiredState object with a new memory and assign the desiredJsonStructure value to finalDesiredState

val finalDesiredState: JSONObject = desiredJsonStructure
Zubair Akber
  • 2,760
  • 13
  • 30
  • This is the same as in Java, i.e. you're copying a reference to an object. If you want to create a new object with the same contents then you need to do so explicitly. See e.g. https://stackoverflow.com/questions/49053432/how-to-clone-object-in-kotlin – Michael Sep 17 '21 at 11:56
  • So there is no other way of assigning the value of variable/object to other object ? – Zubair Akber Sep 17 '21 at 12:19
  • No, in Java/Kotlin there is no passing of objects by value. They are always passed by references. Only primitives are passed by value. It is planned to add value types to Java, but AFAIK it is not yet there. – broot Sep 17 '21 at 12:22

0 Answers0