Immutability and Collections

Array objects that we create with arrayOf() are mutable. Not only can we use [] syntax to retrieve a value based on its index, but we can use []= syntax to replace a value based on its index:

  val thingsArray = arrayOf("foo", "bar", "goo")

  thingsArray[1] = "something completely different"

  println(thingsArray[1])

However, this fails if you try it with a List created using listOf():

val thingsList = listOf("foo", "bar", "goo")

thingsList[1] = "something completely different"

println(thingsList[1])

You get some very strange syntax error messages:

e: klassbook.kt: (4, 1): Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
@InlineOnly public inline operator fun  MutableMap.set(key: Int, value: String): Unit defined in kotlin.collections
e: klassbook.kt: (4, 11): No set method providing array access

The error is raised because listOf() returns a List, which does not have support for the []= operator. A List is immutable: you cannot replace its members with other objects.

If you need a list where you can replace its members, you can use mutableListOf():

  val thingsList = mutableListOf("foo", "bar", "goo")

  thingsList[1] = "something completely different"

  println(thingsList[1])

Here, thingsList is actually a MutableList, which is a sub-type of List that supports []=.

The same distinction holds true for Map. A Map is immutable, but a MutableMap created via mutableMapOf() can be modified.

We will explore more about Kotlin’s philosophy towards immutability in a later chapter. In general, aim to use immutable lists and maps, unless you have a very specific reason to do otherwise.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.