KOTLIN / CHAPTER 06
Collections and transformations
IntermediateSeparate read-only access from mutability and compose useful operations.
By the end of this chapter
- Choose read-only or mutable collection APIs
- Use filter and map
- Preserve order during transformations
The idea
Kotlin distinguishes read-only collection interfaces from mutable interfaces. List offers indexed reading, while MutableList adds update operations. A read-only view does not guarantee that no other reference can mutate the backing object. When a snapshot is required, create a separate collection rather than relying on the declared interface alone. Ordinary list indexing starts at zero.
filter keeps matching elements, and map computes one output for every input it receives. These standard operations return results in encounter order for lists. A lambda can name its parameter explicitly or use it for a single parameter. Write the predicate from the requirement first, then choose the transformation; reversing them can change which values qualify.
fun main() {
val values = listOf(1, 4, 2, 7)
val selected = values.filter { it >= 4 }.map { it * 3 }
println(selected.joinToString(","))
println(values.size)
}12,21 4
Filtering keeps four and seven in that order, then mapping triples them. Neither operation changes the original list of four values.
Try it yourself
Create a list of lengths of nonblank labels while leaving the input untouched.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING