Kotlin Collections

Collections are a central part of Kotlin practice. Prefer immutable collections by default and mutate only when the use case justifies it.

Lists

Kotlin explicitly separates read-only interfaces (List, Map, Set) from mutable ones (MutableList, MutableMap, MutableSet). Exposing read-only interfaces in function return types prevents callers from mutating internal state unexpectedly:

val names: List<String> = listOf("Ada", "Linus", "Kotlin")
val queue = mutableListOf("task-1")
queue.add("task-2")
println("first=${names.first()}, queue=$queue")

Maps

Maps associate unique keys with values. The infix to operator builds Pair entries cleanly for small literals, and bracket lookup returns a nullable value (Int?) when a key might be absent:

val ages = mapOf("Ada" to 36, "Linus" to 55)
val adaAge = ages["Ada"] ?: 0       // safe fallback when key is missing
println("Ada is $adaAge")

Sets

Sets store unique elements and provide O(1) average membership checks when backed by a hash set (setOf(...) uses LinkedHashSet under the hood, preserving insertion order). Reach for sets when deduplicating IDs or checking permissions:

val roles = setOf("editor", "reviewer", "editor") // duplicates dropped
println("count=${roles.size}, canEdit=${"editor" in roles}")

Operations

Standard library transformations such as filter, map, groupBy, and fold return new collections without mutating the source. For large datasets with multiple chained steps, call .asSequence() first so elements flow lazily without allocating intermediate lists at every step:

val words = listOf("kotlin", "java", "rust", "go")
val shortUpper = words
    .asSequence()
    .filter { it.length <= 4 }
    .map { it.uppercase() }
    .toList()
println(shortUpper) // [JAVA, RUST, GO]

Practice

Practice choosing the right collection interface and chaining transformations:

  1. Create a List, a Map, and a Set, and test membership with the in operator.
  2. Chain filter and map over a list of numbers, then convert the pipeline to use asSequence().
  3. Explain why returning List<T> instead of MutableList<T> from a repository method improves encapsulation.