To copy a list in Kotlin, you can use the built-in extension function `toList()` or create a new list and add all elements from the original list.
In this example,
originalList
with some elements.toList()
extension function on originalList
to create a copy of the list.toList()
function returns a new list with the same elements as the original list.fun main() {
val originalList = listOf(1, 2, 3, 4, 5)
val copiedList = originalList.toList()
println("Original List: $originalList")
println("Copied List: $copiedList")
}
Original List: [1, 2, 3, 4, 5] Copied List: [1, 2, 3, 4, 5]
In this example,
originalList
with some elements.copiedList
.originalList
and add each element to copiedList
.copiedList
contains all elements of originalList
.fun main() {
val originalList = listOf("apple", "banana", "cherry")
val copiedList = mutableListOf<String>()
for (item in originalList) {
copiedList.add(item)
}
println("Original List: $originalList")
println("Copied List: $copiedList")
}
Original List: [apple, banana, cherry] Copied List: [apple, banana, cherry]
In this tutorial, we learned How to Copy a List in Kotlin language with well detailed examples.