lannyf
lannyf

Reputation: 11025

Which function to use for making a copy of a list in kotlin

Having a list of Data

val list: List<Data>

And want to make a shallow copy of it into a new list.

There are a few ways could do it in kotlin, wondering which one should be used in which case?

list?.filter is similar to mutableListOf, but listOf seems different.

Anyone suggestion?

val copyData = list?.filter{true}

copyData = mutableListOf(list)

copyData = listOf(list)

Upvotes: 3

Views: 6144

Answers (2)

Roland
Roland

Reputation: 23272

Use filter if you really want to filter the incoming list and work with the filtered one instead. Using filter{true} doesn't really make sense.

Use toMutableList if you need to adapt the returned list, e.g. you need to add additional elements or remove some.

Finally, use toList if you require a new list containing the same elements, which doesn't allow adding/removing elements. You may also want to check the Kotlin reference regarding Collections: List, Set, Map

The ones you mentioned, i.e. mutableListOf and listOf are just convenience methods to create new lists containing whatever you passed.. so you actually constructed a list of lists.

Upvotes: 1

hotkey
hotkey

Reputation: 148001

The latter two options, mutableListOf(list) and listOf(list), don't actually copy a list, they only create a new list which has a single item pointing to the list. This is not a shallow copy of list, because you cannot observe its older content as it changes.

The list.filter { true } option works, i.e. you get a new list that is a copy of list, but it is not an idiomatic solution as it might hurt readability of the code.

Instead, consider list.toList() and list.toMutableList(), based on the desired mutability.

Upvotes: 5

Related Questions