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
:
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.
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:
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.