1. Aggregations: from a collection to a single result
When you start writing real programs (even small console ones), you quickly find out that “get a list” is only half the work. The user (or you) usually wants a final result: a total sum, a maximum value, a minimum value, a concatenated string, a summary by categories. In other words, not “show me all expenses”, but “how much was spent in total” or “what was the most expensive purchase”.
And this is where the typical “beginner magic” happens: someone creates an external var sum = 0, then writes forEach { sum += it } and proudly considers the task solved. Formally, yes. But in terms of style and reliability, it’s like carrying water in your hands: you can deliver it, but the chance of spilling is high—and your hands end up sticky.
fold and reduce give us discipline: we explicitly tell Kotlin, “here is a collection, here is the accumulation rule, return the final result.” This is called aggregation: “many elements → one result”.
The official definition is simple: fold() and reduce() sequentially apply an operation that takes the accumulated value and the next element and returns a new accumulated result.
2. The accumulator: how to read (acc, x) -> newAcc
When you first see fold(0) { acc, x -> acc + x }, it can feel like an incantation. Relax: it’s not magic—just a very honest loop packaged as a function.
The main idea is the accumulator (it’s usually named acc, short for accumulator). This is the value that “accumulates” step by step. At any moment, it stores an intermediate total.
Imagine a piggy bank. Each element of the collection is a coin. acc is how much is already in the piggy bank. On each step you do the same action: take the next coin and update the total.
You can even draw it as a mini diagram:
flowchart LR
A["initial / start"] --> B["acc after the 1st element"]
B --> C["acc after the 2nd element"]
C --> D["acc after the 3rd element"]
D --> E["final result"]
The meaning of the lambda in fold/reduce is always the same: “how to get the next acc from (acc and x)”.
One more important point: the lambda must return the new accumulator value. In Kotlin that means the last expression in the lambda is the returned result (if you don’t write return, which is almost never needed inside lambdas).
If you want to see the “internals” of fold, the documentation often shows an almost literal implementation via a loop: first accumulator = initial, then for each element accumulator = combine(accumulator, element), and at the end accumulator is returned. So it’s not magic—just a neatly packaged for.
3. fold: start value, empty collections, and the neutral element
Up to this point, many collection operations were “safe by contract”: filter on an empty list returns an empty list, count returns 0, and nothing crashes. fold continues this philosophy: it is always defined because it has a start value initial.
Key phrasing: fold(initial) assumes on the first step that the current accumulated value equals initial, and only then starts “absorbing” the elements of the collection. This is exactly how it differs from reduce.
The most basic example: sum of numbers
Sum is a classic because it has a good neutral start: 0.
fun main() {
val xs = listOf(1, 2, 3)
val sum = xs.fold(0) { acc, x -> acc + x }
println(sum) // 6
}
Human-readable version: “start with 0 and for each x add it to acc”.
Why fold is good on empty lists
Here’s where fold is pleasantly calm: an empty list does not cause drama. It simply means “we didn’t add anything to the start,” and the result equals the start value.
fun main() {
val empty = emptyList<Int>()
val sum = empty.fold(0) { acc, x -> acc + x }
println(sum) // 0
}
This is not a bug. This is the contract: fold always returns a value because it always has initial.
| Collection | |
Why |
|---|---|---|
| empty | |
there was not a single update step |
| non-empty | accumulated result | was updated on each element |
The neutral element: why the start must make sense
When a beginner learns fold(0), a dangerous thought appears: “aha, so the start is always 0.” And that’s how programs are born that work consistently—but incorrectly. This is especially tricky: the compiler is silent, there are no errors, but the result is garbage. Computers are excellent at calculating nonsense—that’s one of their strengths.
The purpose of the start value is to be a neutral element (or at least a sensible start) for your operation.
If you compute a product, starting with 0 makes the result 0 forever, because 0 * anything = 0. So we use 1.
fun main() {
val xs = listOf(2, 3, 4)
val product = xs.fold(1) { acc, x -> acc * x }
println(product) // 24
}
The start doesn’t have to be a number—and that’s fine. fold can accumulate any type, because you provide the start. It’s important to understand right now: initial often sets not only the value, but also the result type.
4. reduce: start = first element, and the consequences
reduce looks like “fold, but shorter”: you don’t need to specify the start value. And that’s exactly why reduce is both convenient and slightly dangerous.
The contract of reduce is this: it does not take initial, which means on the first step it must get the initial acc from somewhere. It takes it from the collection: the first element becomes the initial accumulator, and the operation is applied for the first time to the pair (first element, second element).
This leads to two practical consequences: you can’t apply reduce to empty collections, and sometimes reduce gives “the wrong meaning” if you expected every element to be processed uniformly starting from the first one.
Sum via reduce (when the list is definitely not empty)
fun main() {
val xs = listOf(1, 2, 3)
val sum = xs.reduce { acc, x -> acc + x }
println(sum) // 6
}
This works because sum is associative, and “first element as the start” is sensible.
The trap: the first element wasn’t processed like the others
A classic example: “sum the doubled elements.” With fold everything is fair: every element is doubled. With reduce—no, because the first element suddenly becomes the starting acc without being doubled.
Let’s compare:
fun main() {
val xs = listOf(5, 2, 10, 4)
val ok = xs.fold(0) { acc, x -> acc + x * 2 }
val tricky = xs.reduce { acc, x -> acc + x * 2 }
println(ok) // 42
println(tricky) // 37
}
Why?
reduce starts with acc = 5, and then does 5 + 2*2 + 10*2 + 4*2. The first 5 was not doubled because it never went through the “normal rule”—it just became the start.
This is not “Kotlin tricking you”; it’s a direct consequence of the reduce contract.
The most important danger: an empty collection
Since reduce takes its start from the first element, it’s impossible on an empty collection. Therefore, reduce on an empty collection throws an exception (i.e., the program crashes if you don’t handle it).
5. Safe variants and choosing the right approach
When data might be missing, the right model is not “I hope the list isn’t empty,” but “if there is no data, there is no result.” And Kotlin doesn’t try to comfort you here: a safe contract is expressed via a nullable type.
reduceOrNull: the result may be absent
reduceOrNull { ... } does exactly that: if the collection is empty it returns null, and if it’s not empty it works like reduce.
fun main() {
val empty = emptyList<Int>()
val sum = empty.fold(0) { acc, x -> acc + x }
val reduced = empty.reduceOrNull { acc, x -> acc + x }
println(sum) // 0
println(reduced) // null
}
Semantic translation:
- fold says: “a result always exists, even if there is no data (it’s the start value)”.
- reduceOrNull says: “if there is no data, there is no result”.
Both approaches are fine. The choice depends on the task. For sums, “0” is often convenient because 0 means “there was nothing.” But for something like “the smallest purchase,” 0 can be a lie, because a purchase for 0 USDT is suspicious—even during sales.
A practical rule of thumb
If an operation has a natural neutral start (sum → 0, product → 1, string → "", list → emptyList(), etc.), then fold is usually more readable and reliable: it’s defined even on empty data.
If “first element as the start” is logical, and you guarantee a non-empty collection by the meaning of your program, then you can use reduce.
But as soon as that guarantee becomes questionable (user input, filtering, searching), it’s better to switch to reduceOrNull immediately, so the contract is honest and safe.
6. Example from a console app: computing totals
Now we will carefully apply fold/reduceOrNull in our “practical” console app that we developed in the days about collections and commands. Quick reminder of the model: we have a list of operations (for example, expenses) that we are still storing without OOP—just as pairs Pair<String, Int>, where first is the category and second is the amount.
Important: we are not adding new commands or designing architecture here—we are only showing how, in real code, to move “manual math” into readable aggregation functions.
A type for readability (still without classes)
typealias Entry = Pair<String, Int>
Yes, it’s still a Pair, but now there is less noise in the code: List<Entry> is easier to read than List<Pair<String, Int>>.
Total sum via fold(0)
typealias Entry = Pair<String, Int>
fun totalAmount(entries: List<Entry>): Int =
entries.fold(0) { acc, (_, amount) -> acc + amount }
fun main() {
val entries = listOf("food" to 120, "taxi" to 250)
println(totalAmount(entries)) // 370
}
Notice a nice thing: if entries is empty, totalAmount still correctly returns 0, and you don’t need to build an if (entries.isEmpty()) ...
The largest operation via reduceOrNull
Now a more interesting example: find the entry with the maximum amount. Here, a “0” start doesn’t fit: we don’t want to invent a non-existent entry if the list is empty. So the contract “there may be no result” is the honest one.
typealias Entry = Pair<String, Int>
fun maxEntryOrNull(entries: List<Entry>): Entry? =
entries.reduceOrNull { acc, x ->
if (x.second >= acc.second) x else acc
}
fun main() {
val entries = listOf("food" to 120, "taxi" to 250, "food" to 80)
val max = maxEntryOrNull(entries)
println(max) // (taxi, 250)
}
How to print the result without forgetting about null
typealias Entry = Pair<String, Int>
fun maxEntryOrNull(entries: List<Entry>): Entry? =
entries.reduceOrNull { acc, x -> if (x.second >= acc.second) x else acc }
fun main() {
val entries = emptyList<Entry>()
val max = maxEntryOrNull(entries)
println(max?.second ?: 0) // 0
}
Here we are not claiming the maximum purchase is “0”. We are simply saying: “if there is no maximum, for output I’ll show 0”.
This is a subtle but important difference: the internal contract of the function is honest, and output formatting is a separate decision.
7. Common mistakes when working with fold and reduce
Error #1: using reduce where the list can be empty.
This usually happens not “because the person is bad,” but because they wrote a filter and then forgot that the filter can drop everything. The result is a crash out of nowhere. The habit is simple: if you don’t have a rock-solid non-empty guarantee, use fold (when you have a good initial) or reduceOrNull (when there may be no result).
Error #2: choosing the wrong initial and getting a “consistently wrong” result.
fold(0) for sum is great. fold(0) for product is a guaranteed zero. fold(Int.MAX_VALUE) for minimum sometimes works, but it looks like a magic number and breaks if you change the type or the data range. You should be able to explain the start value: what it means and why it doesn’t distort the result.
Error #3: thinking reduce is “the same thing, just shorter,” and not accounting for the first element.
The trap shows up in tasks like “sum of doubled elements”: the first element in reduce becomes the start and doesn’t go through your processing rule. The same lambda in fold and reduce can produce different results precisely because of the start-value contract.
Error #4: mixing up the parameter roles in the lambda and accidentally writing the rule “backwards”.
In fold/reduce, the first parameter is the accumulated value (acc), and the second is the next element (x). If you name them randomly (a, b, c), your brain starts making mistakes by the third line. Simple naming discipline—acc and x (or acc and item)—really reduces the number of bugs.
Error #5: turning an aggregation lambda into a 30-line mini novel.
Technically you can, but it’s hard to read. If complex logic appears inside the aggregation, it’s better to create small local val variables inside the lambda or extract part of the computation into a separate function, and keep only the “glue” in fold/reduce: (acc, x) -> newAcc. A good guideline is to remember that this is essentially a short loop: the logic should be “loop-sized,” not “thesis-sized.”
GO TO FULL VERSION