How to properly copy a list in Kotlin: cloning, copying, and deep copying
Hello everyone! I just started learning Kotlin and encountered an unexpected problem when working with lists.
I have a list of numbers `originalList`, and I want to make a copy of it so that I can modify the copy without affecting the original. I tried simply assigning one list to another:
```kotlin
fun main() {
val originalList = mutableListOf(1, 2, 3, 4, 5)
val copiedList = originalList
copiedList.add(6)
println("Original: $originalList") // [1, 2, 3, 4, 5, 6] — changed!
println("Copied: $copiedList") // [1, 2, 3, 4, 5, 6]
}
```
As you can see, when modifying `copiedList`, `originalList` also changes. This happens because the variable `copiedList` refers to the same object in memory, not to a new copy of the data.
I know that in Java, for copying lists, I used
No answers yet.
Log in to leave an answer
Blogs