Skip to the workspace
Pebellslearn by building
Collections, Ranges and Sequences  ›  Lesson

Read-only vs Mutable Collections

read-only vs mutable 12 minKotlin's List, Set and Map types offer only reading operations, while MutableList, MutableSet and MutableMap add writing ones; read-only means you cannot change it through that reference, not that nobody can.

kotlin / Read-only vs Mutable Collections

Explore each scene at your own pace.

01 · The rule

The rule

Read-only vs Mutable Collections

Kotlin's List, Set and Map types offer only reading operations, while MutableList, MutableSet and MutableMap add writing ones; read-only means you cannot change it through that reference, not that nobody can.

Distinguish a read-only interface from an immutable object and from a mutable collection.

The till adds orders all day. The kitchen screen needs to see those orders but must never delete one by accident. Kotlin solves this with two versions of every collection type: one that only reads and one that also writes.

The rule

Read-only is a locked window, not a frozen room.

Each collection comes in a pair:

Read-only (reading only) Mutable (reading and writing)
List — from listOf MutableList — from mutableListOf
Set — from setOf MutableSet — from mutableSetOf
Map — from mapOf MutableMap — from mutableMapOf

A read-only type simply has no writing functions. listOf("latte").add("chai") does not compile, because List has no add.

A MutableList is also a List, so you can hand a mutable list to someone as read-only:

val orders = mutableListOf("latte")
val kitchenView: List<String> = orders   // same list, read-only window

orders.add("chai")
println(kitchenView)      // [latte, chai] — the kitchen sees it
kitchenView.add("mocha")  // compile error: no add on List

That is the "locked window": the kitchen cannot change the list, but it still sees every change the till makes. Read-only is not the same as immutable. To give someone a frozen snapshot, copy it: orders.toList(). To get an editable copy of a read-only list, use toMutableList().

Do not confuse this with val and var, which are about the variable:

  • val + MutableList → same list forever, contents can change.
  • var + List → contents fixed, but the variable can be pointed at a new list.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.