Accumulate a value by applying an operation from left to right.
The reduce function accumulates a value starting with the first element and applying the given operation from left to right to the current accumulator value and each subsequent element. It throws an UnsupportedOperationException if the collection is empty.
The operation lambda receives two parameters: the current accumulated value and the next element. The result of each invocation becomes the new accumulator.
Use fold when you need to provide an initial value or when the accumulator type differs from the element type.
| Name | Description | Optional |
|---|---|---|
operation |
A lambda with accumulator and element that returns the new accumulator value. | No |
val numbers = listOf(1, 2, 3, 4)
val sum = numbers.reduce { acc, n -> acc + n }
println(sum) // 10