fold() vs reduce() in Kotlin: How the Starting Accumulator Shapes Android Code

The article contrasts Kotlin's fold() and reduce(), which both collapse a collection into a single value but differ in how they begin. fold() takes an explicit seed, so its result type can differ from the element type, while reduce() starts from the first element and requires a compatible type. The author illustrates this with a download-sync example that sums byte counts both ways and builds a transfer report from a list of parts. The piece also notes that reduce() suits merging same-shaped values, such as combining time windows into one covering window. It highlights failure modes like empty collections causing exceptions and overflow in byte totals, all tied to the choice of seed.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in