8

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?

spierce7
  • 14,797
  • 13
  • 65
  • 106

2 Answers2

13

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.

Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148
  • 2
    If you have an ArrayList, and you pass it as a List, that List isn't actually immutable. That's what I meant by that it isn't actually immutable. – spierce7 Jun 02 '15 at 18:37
  • That's right. From a type system point of view however, a mutable list is always an immutable list while the opposite is not the case. – Kirill Rakhman Jun 02 '15 at 21:45
  • Kotlin `List` interface is not `Immutable` but rather `read-only` ... small difference to some, huge to others. `MutableList` is obviously mutable. – Jayson Minard Jan 05 '16 at 11:34
  • I didn't know you could join lists like that, thanks! – Javier Mendonça Aug 10 '17 at 05:31
2

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.

Hadi Hariri
  • 4,656
  • 2
  • 24
  • 13