scan
- Kotlin course
- Advanced
- Lesson 58/83
- 5 min
Learn intermediate results with scan.
Running accumulate with scan
scan is like fold but it collects each intermediate result in a list. It is useful for seeing intermediate states.
Example: listOf(1, 2, 3).scan(0) { acc, n -> acc + n } returns [0, 1, 3, 6]. The initial value is included; each element adds an intermediate sum. While fold yields only the result, scan shows the whole run. This pattern is ideal for running totals and cumulative computations.
scan vs fold
fold returns only the final value. scan returns all intermediate values including the initial one. So a scan result has one more element than the input.
Example: listOf(1, 2, 3).fold(0) { acc, n -> acc + n } gives 6. The same operation with scan gives [0, 1, 3, 6]. Use scan when you want to track progress.
Practice Compute a running total
In main assign the result of listOf(1, 2, 3, 4).scan(0) { acc, n -> acc + n } to a variable and print it with println.
Starter code
// in main compute the running total of 1..4 with scan
// print the result with printlnSample solution
fun main() {
val running = listOf(1, 2, 3, 4).scan(0) { acc, n ->
acc + n
}
println(running)
}Expected output
[0, 1, 3, 6, 10]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does listOf(1, 2, 3).scan(0) { acc, n -> acc + n } return?
- [0, 1, 3, 6] Correct answer
- [1, 3, 6]
- [0, 1, 2, 3]
- [6]
Explanation: scan includes the initial value and all intermediate sums.
2 Match the scan parts
| Term | Meaning |
|---|---|
scan(0) |
Initial value |
{ acc, n -> } |
Lambda |
[0, 1, 3, 6] |
Intermediate results |
fold(0) |
Only final value |
3 Complete the scan call
val running = listOf(1, 2, 3).____(0) { acc, n -> acc + n }
val running = listOf(1, 2, 3).scan(0) { acc, n -> acc + n }
Explanation: scan lists intermediate results with an initial value.