How do you create a copy of a List, that changes r...
# announcements
k
How do you create a copy of a List, that changes references but keeps the objects? I have tried
toList
method but it does not seem to work. Context: I am trying to implement a simple recycler view and update it using DiffUtil, but the oldList and newList are the same for some reason
k
.toList()
makes a shallow copy, the elements aren't copied but the lists themselves are independant.
k
So how do I make a deep copy?
n
generally, by providing a
copy
method for your class. This is not built-in because it's often situation-specific and generic solutions will not be able to handle recursive/self-referencing data structures. Having said that:
list.map{it.copy()}
works if the list contains data class objects (which have a shallow copy method) and you can live with that.