← All languages
Kotlin function of the day
Random

reduce

Accumulate a value by applying an operation from left to right.

Description

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.

Arguments

NameDescriptionOptional
operation A lambda with accumulator and element that returns the new accumulator value. No

Example

val numbers = listOf(1, 2, 3, 4)
val sum = numbers.reduce { acc, n -> acc + n }
println(sum)  // 10

Reference