Kotlin Collections
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:
- Create a
List, aMap, and aSet, and test membership with theinoperator. - Chain
filterandmapover a list of numbers, then convert the pipeline to useasSequence(). - Explain why returning
List<T>instead ofMutableList<T>from a repository method improves encapsulation.