0Pricing
Kotlin Academy · Lesson

fold, reduce, and runningFold

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

fold, reduce, and runningFold is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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
}

fold with a Non-Numeric Seed

The seed can be any type. fold can convert List<T> to a totally different result.

fun main() {
    val words = listOf("hello", "world", "kotlin")
    val joined = words.fold("") { acc, w -> if (acc.isEmpty()) w else "$acc, $w" }
    println(joined) // hello, world, kotlin
}

Basic reduce

reduce uses the first element as the seed. The lambda combines two elements at a time.

fun main() {
    val nums = listOf(2, 3, 4, 5)
    val product = nums.reduce { acc, n -> acc * n }
    println(product) // 120
}

reduce on Empty Lists Throws

reduce requires at least one element. Use reduceOrNull for safety, or prefer fold with a seed.

fun main() {
    val empty: List<Int> = emptyList()
    println(empty.reduceOrNull { a, b -> a + b }) // null
    println(empty.fold(0) { a, b -> a + b })       // 0
}

fold vs reduce

Use fold when you need a different result type or a default value. Use reduce when result type matches element type and the list has at least one element.

fun main() {
    val nums = listOf(1, 2, 3, 4)
    println(nums.reduce { a, b -> a + b })       // 10
    println(nums.fold(100) { a, b -> a + b })   // 110 (seed 100)
}

runningFold

runningFold returns a list of every intermediate accumulator — handy for cumulative sums and step-by-step pipelines.

fun main() {
    val nums = listOf(1, 2, 3, 4)
    val running = nums.runningFold(0) { acc, n -> acc + n }
    println(running) // [0, 1, 3, 6, 10]
}

Cumulative Sum Example

A common analytics pattern: month-over-month cumulative total.

fun main() {
    val monthly = listOf(100, 150, 80, 200, 120)
    val cumulative = monthly.runningReduce { acc, x -> acc + x }
    println(cumulative) // [100, 250, 330, 530, 650]
}

Building a Map with fold

fold a list into a Map by accumulating into a mutable map.

fun main() {
    val words = listOf("apple", "banana", "cherry")
    val byLetter = words.fold(mutableMapOf<Char, MutableList<String>>()) { acc, w ->
        val key = w[0]
        acc.getOrPut(key) { mutableListOf() }.add(w)
        acc
    }
    println(byLetter)
}

Building a List with fold

fold can transform a sequence into a structured list — e.g. group consecutive duplicates.

fun main() {
    val nums = listOf(1, 1, 2, 3, 3, 3, 4)
    val grouped = nums.fold(mutableListOf<MutableList<Int>>()) { acc, n ->
        if (acc.isEmpty() || acc.last().last() != n) acc.add(mutableListOf(n))
        else acc.last().add(n)
        acc
    }
    println(grouped) // [[1, 1], [2], [3, 3, 3], [4]]
}

foldIndexed

Pass the index along with each element — useful for position-aware aggregation.

fun main() {
    val nums = listOf(10, 20, 30)
    val weighted = nums.foldIndexed(0) { i, acc, n -> acc + (i + 1) * n }
    // 1*10 + 2*20 + 3*30 = 140
    println(weighted)
}

reduceRight

reduceRight aggregates from right to left. Matters when the operation is not commutative (e.g., string concatenation order).

fun main() {
    val words = listOf("a", "b", "c", "d")
    val leftToRight = words.reduce { acc, w -> "$acc-$w" }
    val rightToLeft = words.reduceRight { w, acc -> "$w-$acc" }
    println(leftToRight)   // a-b-c-d
    println(rightToLeft)   // a-b-c-d (same here but operation matters)
}

Quick Check

Which function returns a list containing every intermediate accumulator value?

Recap

fold aggregates with a seed (any type). reduce uses the first element as seed (must be non-empty). runningFold / runningReduce return every intermediate value. Use these for sums, products, building maps, grouping, and step-by-step transformations.

Frequently asked questions

Is the “fold, reduce, and runningFold” lesson free?

Yes — the full text of “fold, reduce, and runningFold” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “fold, reduce, and runningFold”?

Aggregate collection elements with fold, reduce, and accumulation functions. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “fold, reduce, and runningFold” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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