androidengineers.Book a session

Collections and Data Structures

Lists: Mutable vs Read-only

article15 minMedium

Read-only access does not establish ownership

List<T> permits reading and iteration; MutableList<T> additionally permits writes. A read-only view can still share mutable backing storage with another owner.

fun main() {
    val source = mutableListOf("Kotlin")
    val view: List<String> = source
    val snapshot = source.toList()
    source.add("Compose")
    check(view.size == 2)
    check(snapshot.size == 1)
}

Return snapshots when callers need stable collection membership. For complex nested objects, a shallow snapshot is insufficient to freeze all state. Consider immutable domain elements or carefully controlled ownership.

Indexing a list assumes an existing position. getOrNull expresses optional access, while first() throws for empty input and firstOrNull() returns null.

Exercise

Implement a repository that privately stores lesson titles, exposes a snapshot, and supports adding a nonblank title. Retrieve a snapshot before a write and confirm it remains unchanged afterward.

Check: callers should have no way to obtain and mutate the repository's original list through its public API.

Reference: Lists

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Lists: Mutable vs Read-only | Kotlin Core Programming | Android Engineers