Part 06 / Topic 2 of 7
Read-only vs mutable: a view, not a copy
List and MutableList are two different interfaces, and the difference matters more than it
first looks. val fixedList = listOf(...) really is fixed underneath — there is no hidden "mutable
version" you can get to, even by forcing a cast past the compiler:
val fixedList = listOf("Rice", "Dal")
try {
@Suppress("UNCHECKED_CAST")
(fixedList as MutableList<String>).add("Ghee")
} catch (e: UnsupportedOperationException) {
println("Casting listOf(...) to MutableList and calling add() failed: ${e.javaClass.simpleName}")
}
Casting listOf(...) to MutableList and calling add() failed: UnsupportedOperationException
But hand a MutableList to someone through a List-typed val, and that List is just a read-only
view of the exact same object — not a snapshot, not a copy. Changes made through the real, mutable
reference show up through the view immediately:
val realCart = mutableListOf("Rice", "Dal")
val readOnlyView: List<String> = realCart
println("Before realCart.add: readOnlyView = $readOnlyView")
realCart.add("Ghee")
println("After realCart.add: readOnlyView = $readOnlyView")
Before realCart.add: readOnlyView = [Rice, Dal]
After realCart.add: readOnlyView = [Rice, Dal, Ghee]
And because it's the same object, casting that view back to MutableList and mutating through the cast
genuinely changes the real list too — this was run for real, not assumed:
@Suppress("UNCHECKED_CAST")
(readOnlyView as MutableList<String>).add("Atta")
println("After cast-and-add: readOnlyView = $readOnlyView, realCart = $realCart")
After cast-and-add: readOnlyView = [Rice, Dal, Ghee, Atta], realCart = [Rice, Dal, Ghee, Atta]
List being read-only is a compile-time promise your own code makes to itself, not a runtime
guarantee the collection enforces on its own — unlike listOf(...)'s genuinely fixed-size backing,
which throws no matter what you cast it to. In practice: accept a List parameter when a function
should only read, and trust that promise without needing !!-style casts of your own — the cast above
exists to show you what's really going on underneath, not as something to write in normal code.
🔍 Going deeper: this is exactly why a function that takes a
List<String>parameter and returns early is still safe from accidental mutation by that function's own code — the type simply doesn't offer.add()to call. It says nothing about whether some other piece of code, holding the same list through aMutableListreference, changes it later.
Full program: examples/02_read_only_vs_mutable.kt.
Done here? The practice set for Part 6 — including the solutions — is on the part page.