Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone or copy a list in kotlin

Tags:

list

copy

kotlin

People also ask

How do you duplicate objects in Kotlin?

For a data class , you can use the compiler-generated copy() method. Note that it will perform a shallow copy. To create a copy of a collection, use the toList() or toSet() methods, depending on the collection type you need. These methods always create a new copy of a collection; they also perform a shallow copy.

What is deep copy in Kotlin?

There is a way to make a deep copy of an object in Kotlin (and Java): serialize it to memory and then deserialize it back to a new object. This will only work if all the data contained in the object are either primitives or implement the Serializable interface.


This works fine.

val selectedSeries = series.toMutableList()

You can use

List -> toList()

Array -> toArray()

ArrayList -> toArray()

MutableList -> toMutableList()


Example:

val array = arrayListOf("1", "2", "3", "4")

val arrayCopy = array.toArray() // copy array to other array

Log.i("---> array " ,  array?.count().toString())
Log.i("---> arrayCopy " ,  arrayCopy?.count().toString())

array.removeAt(0) // remove first item in array 

Log.i("---> array after remove" ,  array?.count().toString())
Log.i("---> arrayCopy after remove" ,  arrayCopy?.count().toString())

print log:

array: 4
arrayCopy: 4
array after remove: 3
arrayCopy after remove: 4

If your list is holding kotlin data class, you can do this

selectedSeries = ArrayList(series.map { it.copy() })

I can come up with two alternative ways:

1. val selectedSeries = mutableListOf<String>().apply { addAll(series) }

2. val selectedSeries = mutableListOf(*series.toTypedArray())

Update: with the new Type Inference engine(opt-in in Kotlin 1.3), We can omit the generic type parameter in 1st example and have this:

1. val selectedSeries = mutableListOf().apply { addAll(series) }

FYI.The way to opt-in new Inference is kotlinc -Xnew-inference ./SourceCode.kt for command line, or kotlin { experimental { newInference 'enable'} for Gradle. For more info about the new Type Inference, check this video: KotlinConf 2018 - New Type Inference and Related Language Features by Svetlana Isakova, especially 'inference for builders' at 30'


Just like in Java:

List:

    val list = mutableListOf("a", "b", "c")
    val list2 = ArrayList(list)

Map:

    val map = mutableMapOf("a" to 1, "b" to 2, "c" to 3)
    val map2 = HashMap(map)

Assuming you're targeting the JVM (or Android); I'm not sure it works for other targets, as it relies on the copy constructors of ArrayList and HashMap.