Partner – Jetbrains – NPI EA (cat = Kotlin Collections)
As a seasoned developer, you’re likely already familiar with
Spring. But Kotlin can take your developer experience with Spring
to the next level!
Join the >> "Advanced Kotlin
Techniques for Spring Developers" webinar and learn how to:
Add new functionality to existing classes with Kotlin extension
Use Kotlin bean definition DSL.
Better configure your application using lateinit.
Use sequences and default argument values to write more
By the end of this talk, you’ll have a deeper understanding of
the advanced Kotlin techniques that are available to you as a
Spring developer, and be able to use them effectively in your
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()
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()
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:
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.