Search code examples
androidlistkotlincompanion-object

Copying elemets from another list (saved in companion object) and modfying them also reflecting modifications to the original companion object


I have an Activity A which has:

class ActivityA {
   companion object {
        var list: MutableList<Person> = //objects are acquired here. 
   }
}

In ActivityB, I copy this list to a variable.

class ActivityB {

    var copyList: MutableList<Person> = ActivityA.list.toMutableList() 
}

After that I am changing some data of the copyList. For example, let's change name of any element. Let's say original list has list.get(0).name = "Bruno". Now, change to something else.

 copyList.get(0).name = "Alex" 

Problem is this is also causing the element at index 0 to be also changed in list. Which means list.get(0).name and copyList.get(0).name has the same names "Alex" now.

How can I make sure that original list elements are not changed even though copyList elements are changed?


Solution

  • You'll need to define a method which makes a copy of Person (and probably of any of its fields recursively or you'll run into a similar problem). If it's a data class, there is already a copy() method, but note it won't copy the fields. And on JVM you can use Cloneable to get a default implementation for non-data classes as described in https://discuss.kotlinlang.org/t/how-to-use-cloneable/2364, but it's generally not recommended.

    Anyway, after you have it,

    var copyList: MutableList<Person> = ActivityA.list.mapTo(mutableListOf<Person>()) { it.copy() }
    

    But this is part of why you should prefer immutability in the first place.