Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Editing List

Tags:

kotlin

What is the best way to edit an immutable List in Kotlin?

I understand that List is not actually immutable, but if I'm passing a List into into a function and I need that entire list minus a single element, is there a supported way to handle that? What about if I want that entire list with an additional element?

like image 363
spierce7 Avatar asked May 28 '15 03:05

spierce7


2 Answers

If you are creating the list yourself, instead of calling listOf("foo", "bar") call mutableListOf("foo", "bar") to get an instance of a MutableList.

If you get the list, e.g. as a parameter to a method, call toMutableList() on it to get a mutable copy.

Alternatively use one of the many built-in extension methods like map() or filter() to get a new list with the modifed elements. For example, to get a list without the first n elements use drop(n). To get only the first n elements call take(n). Here you can find more of the built-in extension methods.

If you need to join two lists, just use the plus operator like this: val newList = list1 + list2.

Note, that modifying lists that are parameters to your methods can be a code smell. That's why all the built-in methods return copies. Also your asumption

I understand that List is not actually immutable

is wrong. As you can see here, the standard library will return an immutable empty list if you call listOf() without arguments.

In Java the List interface is mutable per default which can lead to exceptions when you try to modify an immutable list such as one that was created by calling Arrays.asList(). That's why in Kotlin the opposite is the case.

like image 132
Kirill Rakhman Avatar answered Sep 25 '22 16:09

Kirill Rakhman


If you're dealing with immutable lists, what you want to do is create new lists. So in your case, if you want a list without an element, then filter that element out (in Kotlin you can use the filter function) and return the new list.

like image 22
Hadi Hariri Avatar answered Sep 21 '22 16:09

Hadi Hariri