Search code examples
androidlistarraylistkotlincompanion-object

How to copy companion object and make changes without reflecting these changes to the original object?


I am using companion object to temprorarily save some data.

I might want to change this data and also i want to make sure that original object is not changed when i make changes.

I tried this.

companion object{
        var position: Int = 0
    } 
var copyPosition = positon
copyPosition--
println(copyPosition)

This works perfectly fine and prints -1. Original position is not changed. (value 0 is not changed.)

However, the same operations with List<MyObject> is not working.

companion object{
        var list: MutableList<MyObject> = "...here objects are aquired..."
    } 
var tempList: MutableList<MyObject> = list
tempList.removeAt(0)
println(list.size)

Here, if i remove item from tempList, the original list also loses this item. How can i stop this? How can the changes be only made to tempList but not original list?


Solution

  • You are giving tempList the reference of the list of Companion object. Any changes made are also reflected in the list. What you could do is to create a new MutableList<MyOjbect) and .addAll() all objects of list to your new MutableList object

    Example

    val firstList = mutableListOf(1,2,3,4,5)  //0x543DE (Dummy memory address)
    
    val secondList = firstList  //Giving reference of firstList to the secondList  //0x543DE
    

    As you can see, secondList = firstList, we are giving reference of firstList to the secondList. Think it like this, your firstList val holds a reference to the original list object. And when we wrote secondList = firstList, we are giving secondList with the reference of the list that firstList val was pointing to. Now both of these val point to the same object in the memory.

    Now changes made in secondList are also reflected to the 'original' list. But why? You guessed it, since both of them point to the same object.

    As for the solution, you could:

    companion object{
        var list: MutableList<MyObject> = "...here objects are aquired..."
    } 
    var tempList: MutableList<MyObject> = mutableListOf()
    tempList.addAll(list) //This will iteratively copy list items to tempList
    tempList.removeAt(0)
    println(list.size)