Read-Only Views and Defensive Copies

Read-Only Views and Defensive Copies in Kotlin: --- In the dispatch wing of a hardware wholesaler there is a large pegboard bolted to the wall of the stock…


The Analogy: The Stock-Room Pegboard Behind Glass

In the dispatch wing of a hardware wholesaler there is a large pegboard bolted to the wall of the stock room. Every product line has a labelled hook, and hanging from each hook is a small numbered tag showing how many boxes of that item are currently on the shelves. When a forklift driver brings pallets in, or a picker takes boxes out, one of the floor supervisors unlocks the cabinet, lifts down the old tag, and hangs the new count. The board is the single, living record of what is physically in the room, and it changes many times an hour as goods move.

There are two quite different ways a person can stand in front of that board. The supervisors carry the cabinet key, so they can open the glass front and rehang tags: they hold a writing handle on the board. Everyone else -- auditors, visiting buyers, the new apprentice -- stands on the public side of a fixed glass screen. They can read every tag perfectly well through the glass, but there is no handle on their side of the screen and no key in their pocket, so they cannot move a single tag. They hold a reading handle on the very same board.

The important thing, and the thing people forget, is that the glass screen only stops you from writing. It does nothing to stop the board from changing. An auditor reading through the glass is looking at the identical pegboard the supervisors keep rearranging. If the auditor reads "40 boxes of nails," glances down to note it, and looks up again, the tag may now say "31" because a supervisor pulled nine boxes in the meantime. The glass never promised the auditor a frozen picture; it only ever promised that the auditor's own hands could not disturb the tags.

The failure comes the morning a keen new auditor treats the glass as if it were a photograph. They work methodically along the whole board for twenty minutes, copying each line into their reconciliation sheet, confident that since they cannot change it, it cannot change. But the supervisors were restocking the entire time they wrote. No two of their figures were true at the same instant, and the total they submit describes a stock-room state that never actually existed at any single moment. To get a real snapshot they would have needed to do something the glass could not do for them: photocopy the whole board in one go, or transcribe it and then guard their own sheet, so that later rehangs could not reach back and alter what they had already written down.


Syntax or Core Structure

Kotlin splits every collection into two interfaces. The read-only one -- List, Set, Map -- exposes only inspection members such as size, get, contains, and iteration. The mutable one -- MutableList, MutableSet, MutableMap -- extends its read-only sibling and adds the structural operations: add, remove, set, clear, put. Because MutableList is a List, you can assign a mutable list to a variable typed as read-only. That assignment does not copy anything and does not wrap anything. It is exactly the auditor stepping behind the glass: the same board, a narrower handle.

fun main() {
    val backing: MutableList<String> = mutableListOf("nails", "screws")
    val view: List<String> = backing          // read-only handle onto the SAME list

    println("view sees: " + view)             // reads through the glass
    println("size via view: " + view.size)

    // view.add("bolts")                       // will not compile: List has no add

    backing.add("bolts")                       // a supervisor rehangs a tag
    println("view sees now: " + view)          // the read-only handle reflects it

    println("same object: " + (backing === view))
}

Output:

view sees: [nails, screws]
size via view: 2
view sees now: [nails, screws, bolts]
same object: true

The line backing.add("bolts") never touches view, yet view shows the extra element on the next read. That is the whole lesson in four lines: view was never a snapshot. It is a second reference to the identical object, restricted at compile time to the reading members. The final === prints true because there is only one list on the heap. Read-only means this handle cannot mutate, not this data cannot change.


Technical Depth: Views, Casts, and True Copies

The two interfaces side by side

Every read-only interface is the supertype; every mutable interface adds structural operations on top. Nothing in the read-only interface can change the collection, which is why a variable typed as read-only refuses add at compile time.

Read-only typeMutable subtypeMembers the mutable subtype adds
ListMutableListadd, remove, set, removeAt, clear
SetMutableSetadd, remove, clear, addAll
MapMutableMapput, remove, clear, putAll
CollectionMutableCollectionadd, remove, clear, retainAll

The factory functions follow the same split. listOf, setOf, and mapOf return read-only handles; mutableListOf, mutableSetOf, and mutableMapOf return the writable subtypes. But the declared type of a variable is only a compile-time promise about what that name can do. The object underneath may well be a mutable implementation.

Read-only is not immutable: the downcast escape hatch

Because the runtime object behind a List handle is very often a MutableList, a cast can strip the read-only promise away. The compiler cannot stop this; it only warns, and at runtime the cast simply succeeds.

fun main() {
    val readOnly: List<Int> = mutableListOf(1, 2, 3)   // object is really mutable

    // The declared type forbids mutation...
    // readOnly.add(4)                                  // does not compile

    // ...but a cast reaches the real object underneath.
    val smuggled = readOnly as MutableList<Int>
    smuggled.add(99)

    println("readOnly now: " + readOnly)               // the read-only handle sees it
}

Output:

readOnly now: [1, 2, 3, 99]

The cast worked because mutableListOf really did hand back a MutableList, and widening it to List never changed the object. A genuinely read-only object -- one produced by listOf on some platforms, or by an explicit unmodifiable wrapper -- would instead throw at the first mutation. The point is that you cannot rely on a read-only type to guarantee a read-only object. If you need that guarantee, you must make a copy you control.

Copies snapshot; views stay live

The toList, toMutableList, toSet, and toMap functions each build a brand-new collection by copying the current elements. After a toList snapshot, later mutations to the source cannot reach it. A slice from subList, by contrast, is a live window onto the original storage: change either side and the other sees it.

OperationShares storage with sourceLater source edits visible
toListno, new listno
toMutableListno, new listno
toSetno, new setno
subListyes, same backing arrayyes
fun main() {
    val source = mutableListOf("a", "b", "c")

    val snapshot = source.toList()      // independent copy taken now
    val window = source.subList(0, 2)   // live view over indices 0..1

    source.add("d")                     // mutate the source afterwards

    println("source:   " + source)
    println("snapshot: " + snapshot)    // frozen at the moment of the copy
    println("window:   " + window)      // still a live view of indices 0..1
}

Output:

source:   [a, b, c, d]
snapshot: [a, b, c]
window:   [a, b]

snapshot stayed at three elements because toList copied them out before the add. window still shows two elements because appending "d" happened past its range, but a change inside indices 0..1 would show through immediately -- and structurally editing source while iterating window can throw ConcurrentModificationException. The rule to carry: functions whose names start with to copy, while subList and similar windows do not.


Real World Example: A Shopping Cart That Leaks Its Contents

Consider a Cart class that stores line items in a private mutable list. It is careful on the way in -- the constructor copies the incoming list with toMutableList so that later changes to the caller's list cannot reach inside the cart. But it is careless on the way out: the contents property returns the private backing list directly instead of a copy. This one-sided defence is a common and dangerous shape.

class Cart(initial: List<String>) {
    private val items: MutableList<String> = initial.toMutableList()  // defends input

    fun add(item: String) {
        items.add(item)
    }

    fun total(): Int = items.size

    // FLAW: hands back the live backing list, not a defensive copy.
    val contents: List<String>
        get() = items
}

fun main() {
    val startingItems = mutableListOf("lamp", "rug")
    val cart = Cart(startingItems)

    // Input is defended: mutating the original list does not touch the cart.
    startingItems.add("smuggled")
    println("after source mutated, cart total: " + cart.total())
    println("cart contents: " + cart.contents)

    // A caller captures the read-only contents handle.
    val captured = cart.contents

    // A legitimate cart change bleeds into the captured handle: same object.
    cart.add("mug")
    println("captured after cart.add: " + captured)

    // The graver breach: cast the read-only handle back to mutable and wipe the cart.
    (captured as MutableList<String>).clear()
    println("cart total after caller cleared view: " + cart.total())
}

Output:

after source mutated, cart total: 2
cart contents: [lamp, rug]
captured after cart.add: [lamp, rug, mug]
cart total after caller cleared view: 0

The first two lines show the input defence working: pushing "smuggled" onto startingItems left the cart holding only two items, because toMutableList copied the elements at construction time. If the constructor had written initial as MutableList or simply stored initial, that "smuggled" item would have appeared in the cart. Copying on entry is exactly the auditor transcribing the board onto their own guarded sheet.

The third line is where the leak begins. captured is not a copy of the contents; it is the very same items object that lives inside the cart, handed out under the narrower List type. When the owner calls cart.add("mug"), the mutation shows up through captured because both names point at one list. That is the pegboard again: a read-only handle onto a board that somebody else keeps rehanging.

The fourth line is the real damage. Because the object behind the List handle is genuinely a MutableList, an unfriendly caller can cast the read-only promise away and call clear on the cart's private state. The cart's own encapsulation is bypassed entirely; its total drops to zero without any cart method being called. The concrete design flaw in the code above is the contents getter returning items instead of items.toList(). The fix -- get() = items.toList() -- hands back an independent snapshot, but it is not free: it allocates a new list on every read, which hurts when the cart is large and read in a tight loop, and even then the copy is shallow, so if the elements were mutable objects rather than strings a caller could still reach in and mutate their fields.


Common Mistakes

  1. Believing a read-only type means the data cannot change. A List handle only forbids this reference from mutating. If any other reference to the same object is mutable, the data can change under you at any time. Read-only is about the handle, not the object.
  1. Returning the private mutable list directly from a getter. Writing get() = items on a List-typed property hands out the live backing store. Callers see your later mutations, and can cast the handle back to MutableList and edit your private state. Return items.toList() instead.
  1. Defending only one side. Copying on input but leaking on output (or the reverse) gives a false sense of safety. If isolation matters, copy at both the boundary in and the boundary out.
  1. Assuming toList makes a deep copy. toList copies the references, not the elements. If the elements are mutable objects, both the snapshot and the source point at the same objects, and mutating an element's fields is visible through both.
  1. Treating subList as a copy. subList returns a live view backed by the original list's storage. Edits to either side show through the other, and structurally modifying the source can make the view throw ConcurrentModificationException. Use .subList(a, b).toList() when you want an independent slice.
  1. Casting List to MutableList as a shortcut. It compiles with a warning and often works, but it is fragile: the moment someone passes in a genuinely read-only object, the cast throws ClassCastException or the mutation throws UnsupportedOperationException. Take a toMutableList copy instead.
  1. Exposing a public MutableList property. Declaring val items: MutableList<String> in a public API invites every caller to add and remove at will. Keep the mutable reference private and expose a read-only view or a copy.
  1. Iterating a read-only view while another handle mutates the source. The read-only handle does not protect you from concurrent structural change through a mutable alias; the iterator is still fail-fast and will throw. Snapshot with toList before iterating if the source may change.
  1. Expecting Java's Collections.unmodifiableList to copy. That wrapper is a read-only view over the original list, not a copy. Mutating the underlying list still shows through the wrapper. It is the glass screen, not the photocopy.

Best Practices

  • Keep the mutable reference private and expose only a read-only interface (List, Set, Map) or an explicit copy from the public surface.
  • When true isolation is required, copy defensively on both sides: toMutableList the incoming list in the constructor, and return toList from getters.
  • Reach for toList (or toSet, toMap) whenever you need a snapshot that must not change when the source does.
  • Prefer buildList { ... } to assemble a collection mutably and then hand back a read-only result in one step, keeping the mutable phase local.
  • Never cast a List to MutableList to save an allocation; if you need to mutate, take a toMutableList copy and own it.
  • Document in the API whether a returned collection is a live view or an independent snapshot, so callers know whether later reads can shift under them.
  • Remember that copies are shallow: for genuine deep immutability, make the elements immutable too, using data class types with val properties.
  • Treat subList and other view operations as windows, not copies, and add .toList() at the call site whenever the slice must outlive later edits to the source.

Practice Exercises

  1. Write a Roster class that keeps player names in a private val MutableList, exposes an add method, and exposes the names through a property that callers cannot mutate even by casting. Prove it by attempting the cast in main and observing the result.
  1. Write a function fun labels(): List<Int> that builds its result in a local MutableList and returns it. In main, capture the returned handle and cast it to MutableList; add an element and print the result. Add a comment explaining why the cast succeeds at runtime and how to prevent it.
  1. Create a MutableList of six integers, take subList(1, 4), then set an element of the source inside that range and print both the source and the view. Then repeat with subList(1, 4).toList() and show that the copy no longer tracks the source.
  1. Define data class Box(var count: Int), put three Box values in a list, take a toList snapshot, then mutate count on one of the boxes through the source. Print both lists, explain why the change appears in the snapshot, and state what kind of copy would prevent it.