0Pricing
Kotlin Academy · Lesson

fold, reduce, and runningFold

Aggregate collection elements with fold, reduce, and accumulation functions.

Aggregation Operations

fold and reduce aggregate a collection to a single value. fold accepts a seed; reduce uses the first element as the seed. runningFold returns every intermediate result.

Basic fold

fold(seed) { acc, x -> ... } starts with a seed and combines each element with the accumulator.

fun main() {
    val nums = listOf(1, 2, 3, 4)
    val sum = nums.fold(0) { acc, n -> acc + n }
    println(sum) // 10
}

All lessons in this course

  1. map and flatMap: Transforming Every Element
  2. filter, filterNot, and partition
  3. fold, reduce, and runningFold
  4. Chaining Pipelines and Avoiding Intermediate Lists with Sequence
← Back to Kotlin Academy