1. Overview
In this short tutorial, we’re going to learn how to copy a List in Kotlin.
2. Copying a List
In order to copy a List in Kotlin, we can use the toList() extension function:
val cities = listOf("Berlin", "Munich", "Hamburg")
val copied = cities.toList()
assertThat(copied).containsAll(cities)
As shown above, this function creates a new List and adds all the elements of the source List to it, one after another. Similarly, we can use the toMutableList() extension function to create a mutable collection:
val mutableCopy = cities.toMutableList()
assertThat(mutableCopy).containsAll(cities)
Both extension functions are creating a copy from the source. The only difference is that the latter will return a MutableList after copying.
Please note that these are only creating a shallow copy of the source List. That is, the two List instances are different objects in the Java heap, but their contents are the same objects:
assertThat(copied).isNotSameAs(cities)
assertThat(copied[0]).isSameAs(cities[0])
3. Conclusion
In this tutorial, we learned a couple of ways to copy the contents of a List to another one in Kotlin.
As usual, all the examples are available over on GitHub.