Collections - List, Set and Map

Article · 2:00

The read-only and mutable interfaces, and why the distinction is not the same as immutability.

Kotlin ships two views of every collection. listOf returns a List, which exposes no mutating methods. mutableListOf returns a MutableList, which does. The same split applies to Set and Map. Default to the read-only form and widen only when you need to.

Be precise about what this guarantees. A read-only List is not an immutable list - it is a view that offers no mutating operations. If something else holds a MutableList referring to the same data, it can still change underneath you. Kotlin chose this design for zero-cost Java interoperability; for genuine immutability you want the kotlinx.collections.immutable library.

Choosing between the three types is the usual trade-off. List keeps order and allows duplicates, with indexed access. Set holds each element once and answers membership tests in constant time. Map stores key-to-value pairs, created most readably with the to infix function.

Nullable element access is worth a habit: first() throws on an empty list, firstOrNull() returns null. The same pairing exists for last, max, min and single. Reaching for the OrNull variant and handling the null is almost always better than catching an exception.

fun main() {
    // Read-only by default
    val languages = listOf("Kotlin", "Swift", "Dart", "Kotlin")
    println(languages.size)              // 4 - duplicates kept, order kept
    println(languages[0])                // indexed access

    // A set removes duplicates
    val unique = languages.toSet()
    println(unique)                      // [Kotlin, Swift, Dart]
    println("Swift" in unique)           // true, constant time

    // A map, built with the to function
    val released = mapOf("Kotlin" to 2011, "Swift" to 2014, "Dart" to 2011)
    println(released["Kotlin"])          // 2011
    println(released["Rust"])            // null, not an exception

    // Mutable when you genuinely need it
    val queue = mutableListOf<String>()
    queue.add("build")
    queue += "test"
    println(queue)

    // OrNull instead of an exception on an empty collection
    println(emptyList<Int>().firstOrNull())   // null
}

Discussion

No questions on this topic yet. Sign in to ask the first one.