Dart Fold vs Reduce

Viewed 37337

What's the difference between fold and reduce in Dart and when would I use one as opposed to the other? They seem to do the same thing according to the docs.

Reduces a collection to a single value by iteratively combining each element of the collection with an existing value using the provided function.

2 Answers

There are a few noticeable differences between them. Other than the ones mentioned above, it is worth highlighting that fold() is able to operate on collections that are empty without producing an error.

reduce() will throw an error saying Bad state: No element whereas fold() will return a non-null value back, using the initial value passed onto it as a fallback return value.

I've discussed about this at length here:

https://medium.com/@darsshanNair/demystifying-fold-in-dart-faacb3bd4efd

Related