fold

inline fun <T, R> Iterable<T>.fold(initial: R, operation: (R, T) -> R): R(source)

Accumulates elements in iteration order.

Passes the current accumulator and each element to operation, then uses its result as the next accumulator. An empty iterable returns initial without invoking the operation. Exceptions from iteration or the callback propagate to the caller. The inline callback supports non-local returns.

val total = listOf(1, 2, 3).fold(0) { sum, value -> sum + value }

Receiver

elements to visit in their iteration order.

Return

the final accumulator, or initial when empty.

Parameters

initial

starting accumulator value.

operation

callback receiving the accumulator followed by the current element.