KOTLIN / CHAPTER 12
Lazy sequences and bounded evaluation
AdvancedPredict which transformations actually execute.
By the end of this chapter
- Distinguish eager collection operations from sequences
- Use terminal operations deliberately
- Bound infinite or expensive traversals
The idea
Collection transformations such as List.map eagerly create results, while a Sequence pipeline delays element processing until a terminal operation requests values. The pipeline usually processes each requested element through its stages before moving to the next. This can avoid work when operations such as take stop early, but it also changes when observable side effects occur.
A lazy pipeline is not automatically cached. Repeating a traversal can repeat calculations, so materialize a snapshot with toList when that is the intended contract. Operations differ in how much input they require: sorting generally needs the full source before yielding its ordered output. Place bounds carefully on infinite sequences and avoid claiming that laziness alone makes every combination finite or memory efficient.
fun main(){ var visits=0; val result=sequenceOf(1,2,3,4).map{ visits++; it*2 }.take(2).toList(); println(result);println(visits) }[2, 4] 2
The terminal collection requests only two mapped elements, so later source values are never mapped.
Try it yourself
Compare the number of predicate calls in eager and lazy filter/take pipelines over the same finite input.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING