Kotlin’s fold
and reduce
functions both iterate a collection and feature an accumulator. They differ in how their
accumulators work:
fold
, the accumulator can have any type, and you explicitly specify its initial value. The latter makes fold
safe to use with empty collections.reduce
, the type of the accumulator matches that of the collection elements, and its initial value is the
collection’s first element. For empty collections, an exception is thrown, as there’s no accumulator value to return.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:
If your collection is guaranteed to be nonempty, and reduce
is functionally sufficient, then that’s your best choice.
Otherwise, use fold
: