tezvyn:

Dart reduce versus fold on collections

AI-drafted, machine-checkedintermediate
WHAT IT TESTS

choosing the right aggregation.

OUTLINE

reduce combines same-type elements and throws on empty; fold takes an initial value and accumulator of any type, safe on empty.

RED FLAG

using reduce when the result type differs from the elements.

WHAT THIS TESTS Whether you know how each combiner types its accumulator and how each behaves on an empty collection, then can pick correctly.

A GOOD ANSWER COVERS reduce takes a binary combine function and starts with the first element, folding the rest into it, so the result is always the same type as the elements. With an empty iterable it throws a StateError because there is no first element to seed from. fold takes an explicit initial value plus a combine function whose accumulator can be any type independent of the element type. Because it has a seed, fold returns that seed for an empty collection instead of throwing, and it can transform elements into a different result type.

COMMON WRONG ANSWERS Claiming they are interchangeable. Using reduce to sum a numeric property of a list of objects, which is awkward because the accumulator must stay the element type, not an int. Forgetting that reduce crashes on empty input. Thinking fold cannot change the result type.

LIKELY FOLLOW-UPS What exception does reduce throw on empty. Can fold build a Map. How does generic type inference work for the seed. When is reduce more readable.

ONE CONCRETE EXAMPLE Given a List of Order objects each with a numeric total, you cannot cleanly write orders.reduce because the accumulator would have to be an Order, not a number. Instead you write orders.fold(0, (sum, order) => sum + order.total). Here the seed 0 is an int, the accumulator type differs from the element type Order, and if orders is empty the call safely returns 0 rather than throwing. reduce fits only when the result is the same type as the elements, such as numbers.reduce((a, b) => a + b) on a non-empty list of ints.

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.