Immutability
suggest changeAn immutable object can't change after it has been created. Kotlin encourages immutability more than Java does, but the language mostly gives you read-only building blocks, not truly immutable ones. The difference matters:
valmakes a reference read-only. The object it points to may still change.List,SetandMapare read-only interfaces. The object behind them may be a mutableArrayListthat someone else is still changing.- A
data classwith onlyvalproperties is immutable only if the types of those properties are immutable too.
This article shows where each of these guarantees ends and how to build values that really can't change: immutable classes, defensive copies, persistent collections from kotlinx.collections.immutable, and sharing immutable state between threads.
val is a read-only reference
A val can't be reassigned, but that doesn't make it constant. For a basic introduction to val, var and references see Values and references.
A val property with a custom getter can return a different value on every read:
class Temperature(var celsius: Double) {
val fahrenheit: Double
get() = celsius * 9 / 5 + 32
}
fun main() {
val t = Temperature(20.0)
println(t.fahrenheit)
t.celsius = 30.0
println(t.fahrenheit) // same val, different value
}
68.0
86.0
val means "you can't assign to this", not "this never changes". Only a val backed by a field and holding an immutable value is truly fixed.
For true compile-time constants of primitive types and String, use const val. The compiler inlines the value at every use site:
object Limits {
const val MAX_USERS = 100 // compile-time constant
val startedAt = System.nanoTime() > 0 // read-only, computed at runtime
}
@JvmInline
value class Email(val value: String) {
init {
require("@" in value) { "invalid email: $value" }
}
fun domain(): String = value.substringAfter('@')
}
fun main() {
println(Limits.MAX_USERS)
val e = Email("ann@example.com")
println(e.domain())
val upper = "kotlin".uppercase() // strings are immutable: a new string
println(upper)
}
100
example.com
KOTLIN
String, numbers, Boolean, Char, java.time types such as LocalDate and Instant, BigDecimal and value classes like Email above are all immutable. A value class can only hold val properties, which makes it a cheap way to create small immutable domain types.
Read-only collections are not immutable
List<T> has no add or remove, so it looks immutable. It is really a read-only view. A MutableList is also a List, so the same object can be seen through both types:
fun main() {
val backing = mutableListOf("a", "b")
val view: List<String> = backing // read-only view, same object
println(view)
backing.add("c")
println(view) // the "read-only" list changed
// A read-only type can be cast back to a mutable one
(view as MutableList<String>).add("d")
println(backing)
}
[a, b]
[a, b, c]
[a, b, c, d]
Two problems are visible here:
- whoever holds the
MutableListcan change the list under the reader's feet - the reader can cast it back to
MutableListand change it
Even listOf() doesn't return a truly immutable list on the JVM. With several elements it returns java.util.Arrays$ArrayList, a fixed-size wrapper over an array that supports set():
fun main() {
val nums = listOf(1, 2, 3)
println(nums.javaClass.name)
val sneaky = nums as MutableList<Int>
sneaky[0] = 100 // set() works on this implementation
println(nums)
try {
sneaky.add(4) // add() does not
} catch (e: UnsupportedOperationException) {
println("add failed: $e")
}
}
java.util.Arrays$ArrayList
[100, 2, 3]
add failed: java.lang.UnsupportedOperationException
Casting a read-only collection to a mutable type is a bug in the caller, and normal Kotlin code never does it. But the example shows that the read-only interfaces are a compile-time convention, not runtime protection. This matters when you pass collections to Java code, which sees every List as a java.util.List with add and set.
Taking a snapshot
To get a list nobody else can change, copy it. toList() creates an independent copy. Java's List.copyOf() creates a copy that also rejects every modification at runtime:
fun main() {
val source = mutableListOf(1, 2, 3)
val snapshot = source.toList() // independent copy
val javaImmutable = java.util.List.copyOf(source)
source.add(4)
println(source)
println(snapshot)
println(javaImmutable)
try {
(javaImmutable as MutableList<Int>).add(5)
} catch (e: UnsupportedOperationException) {
println("List.copyOf rejects changes: ${e.javaClass.simpleName}")
}
}
[1, 2, 3, 4]
[1, 2, 3]
[1, 2, 3]
List.copyOf rejects changes: UnsupportedOperationException
toList() usually returns an ArrayList, so a cast would let a caller change the copy, but that no longer affects the original. Java's Set.copyOf() and Map.copyOf() work the same way as List.copyOf(). None of them accept null elements.
A copy is shallow: the list is new, but its elements are shared. A list of immutable values (strings, numbers, immutable data classes) is fully immutable; a list of mutable objects is not. See Copying and cloning for shallow vs deep copies.
Building collections without mutation
Most code doesn't need a mutable collection at all. Transformations like map, filter, sorted and the + operator return new collections and leave the original alone. When a loop is the clearest way to fill a collection, buildList, buildSet, buildMap and buildString keep the mutable builder local and hand out a read-only result:
fun main() {
val squares = buildList {
for (i in 1..5) add(i * i)
}
val index = buildMap {
put("one", 1)
put("two", 2)
}
val csv = buildString {
append("id,name\n")
append("1,Ann")
}
println(squares)
println(index)
println(csv)
val words = listOf("b", "a", "c")
val sorted = words.sorted() // new list
val more = words + "d" // new list
println("$words $sorted $more")
}
[1, 4, 9, 16, 25]
{one=1, two=2}
id,name
1,Ann
[b, a, c] [a, b, c] [b, a, c, d]
No reference to the mutable builder escapes the lambda, so nobody can change squares or index later. See Using list and Using map for more collection operations.
Arrays are always mutable
There is no read-only array type. Any code with a reference to an array can change its elements. asList() gives a List view backed by the array, which changes along with it; toList() copies:
fun main() {
val arr = arrayOf(1, 2, 3)
arr[0] = 100 // allowed: arrays are always mutable
println(arr.contentToString())
val list: List<Int> = arr.asList() // a view backed by the array
arr[1] = 200
println(list)
val safe = arr.toList() // a copy
arr[2] = 300
println(safe)
}
[100, 2, 3]
[100, 200, 3]
[100, 200, 3]
Prefer List over Array in public APIs. If you must store an array you received, copy it with copyOf().
Immutable classes
An immutable class has only val properties, and each property holds an immutable value. A data class is the natural fit: it gives you equals, hashCode, toString and a copy() function to create modified versions.
data class Address(val street: String, val city: String)
data class Customer(
val id: Int,
val name: String,
val address: Address,
) {
init {
require(name.isNotBlank()) { "name must not be blank" }
}
}
fun main() {
val c1 = Customer(1, "Ann", Address("1 Main St", "Springfield"))
// "Change" a nested property by copying each level
val c2 = c1.copy(address = c1.address.copy(city = "Shelbyville"))
println(c1)
println(c2)
println(c1.address === c2.address)
try {
c1.copy(name = " ")
} catch (e: IllegalArgumentException) {
println("copy() runs init too: ${e.message}")
}
}
Customer(id=1, name=Ann, address=Address(street=1 Main St, city=Springfield))
Customer(id=1, name=Ann, address=Address(street=1 Main St, city=Shelbyville))
false
copy() runs init too: name must not be blank
Benefits of immutable classes:
- validation once: the
initblock checks the invariants, and sincecopy()goes through the constructor, no instance can ever be invalid - safe sharing: you can pass the object anywhere, store it in a cache or send it to another thread without copying
- safe map keys and set elements:
hashCodecan't change after the object is inserted into aHashMaporHashSet - easy reasoning: a function that receives a
Customercan't change the caller's object
The leaky List property
A val property of type List is the most common hole in an "immutable" class. The caller may still hold the mutable list it passed in:
data class Playlist(val name: String, val songs: List<String>)
fun main() {
val songs = mutableListOf("Song A", "Song B")
val playlist = Playlist("Road trip", songs)
songs.add("Song C") // the caller still holds the mutable list
println(playlist)
}
Playlist(name=Road trip, songs=[Song A, Song B, Song C])
There are two fixes. A regular class can make a defensive copy in the constructor. Or the property can use a type that is immutable by contract, such as ImmutableList from kotlinx.collections.immutable (covered below), so the caller has to make the conversion:
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
class Playlist(val name: String, songs: List<String>) {
val songs: List<String> = songs.toList() // defensive copy
}
data class Playlist2(val name: String, val songs: ImmutableList<String>)
fun main() {
val songs = mutableListOf("Song A", "Song B")
val p1 = Playlist("Road trip", songs)
val p2 = Playlist2("Road trip", songs.toImmutableList())
songs.add("Song C")
println(p1.songs)
println(p2.songs)
}
[Song A, Song B]
[Song A, Song B]
A defensive copy doesn't work well with a data class, because every primary constructor parameter must be a property, so there is nowhere to put the copy. That's the main reason to use ImmutableList in data classes.
Exposing mutable state safely
Sometimes a class needs mutable state internally. The usual pattern is a private mutable collection and a public read-only property. Decide whether the public property should be a view or a snapshot:
class ShoppingCart {
private val _items = mutableListOf<String>()
// Read-only view: cheap, but callers see later changes and can cast it
val itemsView: List<String> get() = _items
// Snapshot: a copy, so whatever callers do with it can't affect the cart
val items: List<String> get() = _items.toList()
fun add(item: String) {
_items += item
}
}
fun main() {
val cart = ShoppingCart()
cart.add("milk")
cart.add("eggs")
val view = cart.itemsView
val snapshot = cart.items
cart.add("bread")
println("view: $view")
println("snapshot: $snapshot")
(view as MutableList<String>).clear() // empties the real cart!
println("cart after view cast: ${cart.items}")
cart.add("tea")
cart.add("jam")
(cart.items as MutableList<String>).clear() // only clears a copy
println("cart after snapshot cast: ${cart.items}")
}
view: [milk, eggs, bread]
snapshot: [milk, eggs]
cart after view cast: []
cart after snapshot cast: [tea, jam]
A view costs nothing and is fine inside your own code base. A snapshot costs a copy on every read, but it is the safe choice for public library APIs and for state that other threads read while the class keeps changing it. Iterating over a view of an ArrayList while another thread adds to it can throw ConcurrentModificationException, or worse, silently give wrong results.
Persistent collections with kotlinx.collections.immutable
kotlinx.collections.immutable is the official JetBrains library for immutable collections. Add it to Gradle:
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-collections-immutable:0.5.2")
}
It provides two families of interfaces:
ImmutableList,ImmutableSet,ImmutableMap: read-only collections that are guaranteed never to changePersistentList,PersistentSet,PersistentMap: immutable collections with operations that return a modified copy
The copies are cheap. A persistent collection is a tree that shares most of its structure with the previous version, so adding an element to a 100,000-element list doesn't copy 100,000 references.
import kotlinx.collections.immutable.*
fun main() {
val v1: PersistentList<String> = persistentListOf("a", "b")
val v2 = v1.adding("c") // returns a new list
val v3 = v2.replacingAt(0, "A").removingAt(1)
println(v1)
println(v2)
println(v3)
// Batch several changes efficiently with a builder
val v4 = v2.mutate { list ->
list.add("d")
list.removeAll { it == "b" }
}
println(v4)
val prices = persistentMapOf("apple" to 1.0, "pear" to 2.0)
val updated = prices.putting("apple", 1.5).removing("pear")
println(prices)
println(updated)
// Converting from regular collections
val tags: ImmutableSet<String> = listOf("x", "y", "x").toImmutableSet()
println(tags)
println(v1 is MutableList<*>)
}
[a, b]
[a, b, c]
[A, c]
[a, c, d]
{apple=1.0, pear=2.0}
{apple=1.5}
[x, y]
false
Notes:
- In version 0.5 the modifying functions got new names:
adding,addingAll,removing,removingAt,replacingAt,putting,cleared. The old names (add,set,removeAt,put,remove) still compile but are deprecated, because code likelist.add(x)that ignores the result looked like a mutation and was a common bug. Older code and tutorials use the old names. mutate { }gives you a mutable builder and returns a new persistent collection when the lambda ends. Use it for many changes in a row, since it avoids creating an intermediate version per change.toImmutableList(),toImmutableSet(),toPersistentList()andtoPersistentMap()convert regular collections. If the input already is an immutable collection, no copy is made.- Persistent collections implement the regular
List,SetandMapinterfaces, so you can pass them to any function that takes a read-only collection. - In Jetpack Compose,
ImmutableListparameters are treated as stable, while a plainListparameter is not, which can prevent unnecessary recomposition.
Immutability and concurrency
Immutable objects are thread-safe by construction: there is nothing to synchronize when nobody can write. Shared state still has to change, though. A good pattern is to keep the whole state in one immutable object and replace it atomically with an updated copy:
import java.util.concurrent.atomic.AtomicReference
import kotlin.concurrent.thread
data class Stats(val requests: Int = 0, val errors: Int = 0, val lastPath: String = "")
class Metrics {
private val state = AtomicReference(Stats())
fun record(path: String, failed: Boolean) {
state.updateAndGet { s ->
s.copy(
requests = s.requests + 1,
errors = if (failed) s.errors + 1 else s.errors,
lastPath = path,
)
}
}
// Readers get a consistent snapshot without locking
fun snapshot(): Stats = state.get()
}
fun main() {
val metrics = Metrics()
val threads = (1..8).map { n ->
thread {
repeat(10_000) { i -> metrics.record("/t$n", failed = i % 10 == 0) }
}
}
threads.forEach { it.join() }
val s = metrics.snapshot()
println("requests=${s.requests} errors=${s.errors}")
}
requests=80000 errors=8000
updateAndGet reads the current Stats, computes a new one and swaps it in only if no other thread changed the reference in the meantime; otherwise it retries. That's why the update lambda must have no side effects: it may run more than once. Readers always see a complete Stats object, never one where requests was updated but errors wasn't.
The same idea is behind MutableStateFlow.update { it.copy(...) } in coroutines code. Whether you use an AtomicReference or a StateFlow, it only works if the state object is really immutable: putting a MutableList inside Stats would bring the data races back. See Race conditions for other ways of protecting shared mutable state.
Summary
- Use
valby default, but remember it only prevents reassignment. Avalwith a getter, or one that holds a mutable object, can still change. List,SetandMapare read-only views, not immutable collections. Keep mutable collections private and return snapshots (toList()) or immutable collections from public APIs.- Build collections with
map,filter,+andbuildList/buildMapinstead of mutating a shared one. - Arrays are always mutable; prefer
Listin APIs and copy arrays you receive. - Make classes immutable with
valproperties of immutable types, validate ininit, and create modified versions withcopy(). - Protect
Listproperties with a defensive copy or withImmutableListfromkotlinx.collections.immutable; usePersistentListandPersistentMapwhen you need cheap modified copies of large collections. - For shared state, replace a whole immutable snapshot atomically instead of locking around mutable fields.