Immutability (Kotlin)
Immutability means data can't change after creation. Kotlin encourages it through read-only val bindings and read-only collection interfaces, making code safer and easier to reason about.
Kotlin
Kotlin nudges you toward immutability at two levels: val for references that can't be reassigned, and read-only collection types (List, Map, Set) that don't expose mutators. Data classes with val properties plus copy() let you 'change' values by producing new instances.
Immutable data is inherently thread-safe — no synchronization is needed because nothing can change it — which matters a lot with coroutines and shared state. It also eliminates a whole class of bugs where a value changes unexpectedly under your code.
Be aware of the limits: a val only freezes the reference, not the object, and a read-only List can still be backed by a mutable one elsewhere. True deep immutability requires immutable element types throughout. Still, preferring val and read-only collections by default is core idiomatic Kotlin.
Examples
Kotlin
data class Account(val balance: Int)
val a = Account(100)
val b = a.copy(balance = a.balance + 50)
println(a)
println(b)Output:
Account(balance=100)
Account(balance=150)