Kotlin

Immutable vs Mutable Collections

admin by @admin ADMIN
5d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`listOf` / `setOf` / `mapOf` build READ-ONLY views; `mutableListOf` / `mutableSetOf` / `mutableMapOf` are mutable. Default to immutable — the call site is a contract about intent.
Kotlin
Raw
fun main() {
    val readOnly: List<Int> = listOf(1, 2, 3)
    // readOnly.add(4)                  // ✗ compile error — no `add` method on List

    val mutable: MutableList<Int> = mutableListOf(1, 2, 3)
    mutable.add(4)
    mutable.removeAt(0)
    println(mutable)                     // [2, 3, 4]

    // Maps
    val cfg: Map<String, Int> = mapOf("port" to 8080, "timeout" to 5000)
    val edit: MutableMap<String, Int> = cfg.toMutableMap()
    edit["port"] = 9090

    // Sets
    val tags = setOf("a", "b", "c")
    val moreTagsCopy = tags + "d"          // immutable + element → NEW Set

    // Snapshot a mutable → immutable view
    val frozen: List<Int> = mutable.toList()
    println(frozen)                        // [2, 3, 4]
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.