fold and reduce
- Kotlin course
- Intermediate
- Lesson 65/116
- 5 min
Learn aggregation with fold and reduce.
fold and reduce
fold performs an associative operation with an initial value. Example: numbers.fold(0) { acc, n -> acc + n } computes the sum. acc is the accumulator and n is the current element. The initial value makes the empty list case safe.
reduce takes no initial value; the first element acts as the start. Example: numbers.reduce { a, b -> a + b }. On an empty list reduce throws because there is no starting element. For operations like a sum that always need a start, prefer fold.
fold versus reduce
The main difference between fold and reduce is the initial value. fold takes an explicit start, which can even have a different type than the list. Example: numbers.fold("") { acc, n -> acc + n.toString() } joins numbers into a string.
reduce uses the first element as the start, so the result type must match the list type. On an empty list reduce throws a NoSuchElementException. For a safe sum use fold(0); when the first element is the natural start, choose reduce.
Practice Sum with fold, find max with reduce
Define val numbers = listOf(3, 1, 4, 1, 5). Compute the sum with fold(0) { acc, n -> acc + n }. Find the largest element with reduce { a, b -> if (a > b) a else b }. Print the result as println("Sum: $sum, Max: $max").
Starter code
fun main() {
val numbers = listOf(3, 1, 4, 1, 5)
// Compute sum with fold, max with reduce, and print
}Sample solution
fun main() {
val numbers = listOf(3, 1, 4, 1, 5)
val sum = numbers.fold(0) { acc, n -> acc + n }
val max = numbers.reduce { a, b -> if (a > b) a else b }
println("Sum: $sum, Max: $max")
}Expected output
Sum: 14, Max: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the fold call
numbers.____(0) { acc, n -> acc + n }
numbers.fold(0) { acc, n -> acc + n }
Explanation: fold(0) computes the sum starting from zero.
2 Match the fold and reduce concepts
| Term | Meaning |
|---|---|
fold(0) |
Has initial value |
reduce |
First element starts |
acc |
Accumulator |
{ acc, n -> } |
Operation |
3 What does reduce do on an empty list?
- Throws an exception Correct answer
- Returns zero
- Returns null
- Returns an empty list
Explanation: reduce throws NoSuchElementException on an empty list.