Avatar ·

How to copy or clone a list in Kotlin: complete guide

Hi! I just started learning Kotlin after Java, and I have a problem with copying lists.\n\nIn Java, I was used to doing something like `new ArrayList<>(originalList)` to create an independent copy. But in Kotlin, I noticed that simple assignment `val copy = originalList` doesn't create a copy, just a reference to the same object. I tried `originalList.toList()`, but when I change elements in the copy, the changes still reflect in the original? Or am I confusing something?\n\nHere's an example that confuses me:\n\n```kotlin\ndata class Person(val name: String, var age: Int)\n\nfun main() {\n val original = mutableListOf(Person("Alice", 25), Person("Bob", 30))\n val copy = original.toList() // is this a copy?\n \n // Trying to change\n (copy as MutableList)[0].age = 26 // Changing th