# Kotlin: fold vs. reduce

The difference between the two collection functions.

May 27, 2022

Kotlin’s fold and reduce functions are, at first glance, quite similar: they both iterate a collection, and they both feature an accumulator. So you may find yourself wondering what the difference between the two functions is, and when each one should be used.

There are two main differences between fold and reduce:

1. fold lets you define a custom initial value for the accumulator. In contrast, with reduce, the initial value of the accumulator is the first value from the collection, and the first call to the lambda occurs for the second element of the collection.

2. fold can be safely called on an empty collection, and reduce throws an exception in such an instance (because the initial value cannot be determined, and thus nothing can be returned).

If you were to calculate the product of all the integers included in a list, both fold and reduce would do the job, but reduce would be more concise:

.css-k1eqs8{font-family:"IBM Plex Mono",monospace;font-size:16px;line-height:24px;font-weight:400;}listOf(8, 16, 24).reduce { product, integer ->    product * integer}
listOf(8, 16, 24).fold(initial = 1) { product, integer ->    product * integer}

However, when the first element of the collection at hand cannot be the first value of the accumulator, fold is your best friend. The same is true for instances where you cannot guarantee that a collection isn’t going to be empty.

listOf(Person.John, Person.Mary, Person.Anne)    .fold(initial = 0) { ageSum, person ->        ageSum + person.age    }

© 2018–2023 Patrick Michalik

GitHub