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.
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.