Patrick Michalik

Kotlin: fold vs. reduce

Kotlin’s fold and reduce functions both iterate a collection and feature an accumulator. They differ in how their accumulators work:

fold is thus more powerful than reduce. It can handle all the same operations and many more. The use case for reduce is performing simple calculations more elegantly—consider this comparison:

listOf(8, 16, 24).fold(initial = 1) { product, integer ->
    product * integer
}
listOf(8, 16, 24).reduce { product, integer -> product * integer }

If your collection is guaranteed to be nonempty, and reduce is functionally sufficient, then that’s your best choice. Otherwise, use fold:

listOf(Person.John, Person.Mary, Person.Anne)
    .fold(initial = 0) { totalAge, person -> totalAge + person.age }
© 2024 Patrick Michalik