Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 10 / Topic 6 of 8

fold and reduce

fold(initial) { acc, element -> ... } walks a collection left to right, carrying an accumulator that starts as initial. It can produce a different type than the elements:

val totalWeight = SHIPMENTS.fold(0.0) { acc, s -> acc + s.weightKg }   // Double out of List<Shipment>

reduce { acc, element -> ... } is fold without an explicit initial — it seeds the accumulator with the collection's first element instead, so the accumulator's type must match the element type, and it has nothing to seed with on an empty collection:

val heaviestByReduce = SHIPMENTS.reduce { acc, s -> if (s.weightKg > acc.weightKg) s else acc }
Total weight (fold): 4015.25 kg
Heaviest (reduce): S-2004
reduce on an empty list threw UnsupportedOperationException
fold on an empty list: 0.0 (no exception)
Weight by city (fold into a map): {Pune=1295.25, Mumbai=320.0, Chennai=2400.0}

fold has no such gap — it already has initial to fall back on with zero elements. The last example folds into a MutableMap<String, Double> instead of a number, proving fold's accumulator can be any shape at all, not just a running total.

Rule of thumb: reach for fold whenever you need a seed value, a different result type, or a safe answer on an empty collection; reach for reduce only when the elements and the result are naturally the same type and an empty collection genuinely shouldn't occur.

Full program: examples/06_fold_and_reduce.kt.

Done here? The practice set for Part 10 — including the solutions — is on the part page.

Search the guide