Kotlin: Collections & Lambdas
What you will learn
Kotlin's powerful functional collection operations, the distinction between read-only and mutable collections, and the implicit lambda parameter it.
Creating collections
val numbers = listOf(1, 2, 3, 4, 5) // read-only List<Int>
val mutableNumbers = mutableListOf(1, 2, 3) // MutableList<Int>
val set = setOf("a", "b", "c") // read-only Set
val map = mapOf("key" to "value") // read-only Map
Kotlin separates read-only and mutable at the type level. listOf() returns List<T> (read-only); mutableListOf() returns MutableList<T>.
Lambda operations
val even = numbers.filter { it % 2 == 0 } // [2, 4]
val doubled = numbers.map { it * 2 } // [2, 4, 6, 8, 10]
val sum = numbers.reduce { acc, n -> acc + n } // 15
val anyBig = numbers.any { it > 4 } // true
val sortedDesc = numbers.sortedDescending() // [5, 4, 3, 2, 1]
The it keyword is the implicit parameter name when a lambda has exactly one parameter. For multiple parameters, name them explicitly: { acc, n -> ... }.
Sequence (lazy evaluation)
For large collections, use asSequence() to avoid creating intermediate lists:
numbers.asSequence()
.filter { it > 2 }
.map { it * 2 }
.toList()
Common mistakes
- Calling
.add()on alistOf()result — it's read-only! UsemutableListOf()or+=which creates a new list. - Forgetting that
map { ... }on aMapiterates over entries, not keys — use.keysor.valuesif that's what you need. - Chaining many operations on large lists without
.asSequence()— each step creates a new list.
Quick check below!