@here Hi Guys I have an issues with memory allocat...
# android
m
@here Hi Guys I have an issues with memory allocation this is my simplified version of what I do in my app
Copy code
data class Foo(var bar: String, var listFoos: MutableList<String>)
    val foos = mutableListOf("one", "due", "three")
        val pair = Pair(Foo("bar", foos), mutableListOf("ignore", "me"))

        val pairCopy = pair.copy()

        info { "Pair " + pair.second + "and :" + pair.first.listFoos }
        info { "Pair Copy" + pairCopy.second + "and :" + pairCopy.first.listFoos }
        pairCopy.second.clear()
        pairCopy.first.listFoos.clear()
        pairCopy.first.bar = "SUCKIT"

        info { "Pair Copy Cleared " + pairCopy.second.toString() + "and :" + pairCopy.first.listFoos.toString() }
        info { "Pair: " + pair.second + "and :" + pair.first.listFoos }
        info { "Pair  Bar property: " + pair.first.bar }
no matter what I do the list on the first pair is cleared, I supposed that the copy method reallocate the pair object, which does work just for no list type what to do ?
u
Copy is just a shallow copy so you wont actually copy the list but rather copy the reference to the list. I would manually create a copy of the list and set the list to the newly created list when copying
I would generally avoid the copy method when dealing with objects that have mutable nonprimitive values. Effective java suggests that you create a copy constructor or a copy factory method for such classes. I tend to feel like this is also a good recommendation for kotlin.
m
Thanks for the answer, much appreciated, I ended up in writing a manual clone extension method I noticed that if you transfer object from a list to an another you get the same result as copying the list.. which was quite disappointing 🙂 so I basically rewrote a manual copy. thanks a lot