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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With