Search code examples
androidkotlinandroid-recyclerviewlistadapter

modifying child object of list in kotlin but list is equal to not modifed


I have a data class like this

data class TestModel(val id: Int, val sentence: String , var isPlaying: Boolean)

And I make a mutableList of that

val list: MutableList<TestModel> = arrayListOf(
    TestModel(1,"test",false),
    TestModel(2,"test2",false),
    TestModel(3,"test3",false))

then make a copy of the list in another object

val list2=list

when I modify list, for example:

list2[0].isPlaying=true

if I check the equality of these two lists

print(list==list2)

the result will be true while data in list is modified

I use this list in Android ListAdapter and while list is as same as old list, the adapter will not understand I have do some modifying.

How I can achieve what I want? thanks for your response


Solution

  • In that case you are modifying also the data classes of the original list. So if you print both lists you will get the same results:

    list: [TestModel(id=1, sentence=test, isPlaying=true), TestModel(id=2, sentence=test2, isPlaying=false), TestModel(id=3, sentence=test3, isPlaying=false)]

    list2: [TestModel(id=1, sentence=test, isPlaying=true), TestModel(id=2, sentence=test2, isPlaying=false), TestModel(id=3, sentence=test3, isPlaying=false)]

    You need to make a copy of each of the data classes to have the results that you want otherwise you will be referring to the same data classes of the original list and both will have the same data

    For that, you can use this function if you want or something to make a copy of those data classes:

    fun MutableList<TestModel>.copyOf(): MutableList<TestModel> {
        return this.map { it.copy() }.toMutableList()
    }
    

    And use it like this:

    val list = mutableListOf(
        TestModel(1,"test",false),
        TestModel(2,"test2",false),
        TestModel(3,"test3",false)
    )
    val list2=list.copyOf()
    list2[0].isPlaying=true
    println(list==list2)
    

    Hope this helps!