Kotlin

fold and scan

admin by @admin ADMIN
just now
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`fold` accumulates from a seed across all items. `runningFold` / `scan` yields every intermediate accumulator value — running totals, cumulative metrics.
Kotlin
Raw
fun main() {
    val nums = listOf(1, 2, 3, 4, 5)

    // fold — explicit initial value (handles empty input)
    val sum     = nums.fold(0)  { acc, n -> acc + n }
    val product = nums.fold(1)  { acc, n -> acc * n }
    println("$sum $product")                            // 15 120

    // Sum + count in a single pass with a Pair accumulator
    val (total, count) = nums.fold(0 to 0) { (s, c), n -> (s + n) to (c + 1) }
    println("avg = ${total.toDouble() / count}")        // avg = 3.0

    // runningFold — yields the accumulator at each step (Kotlin 1.4+)
    val running = nums.runningFold(0) { acc, n -> acc + n }
    println(running)                                    // [0, 1, 3, 6, 10, 15]

    // scan — alias for runningReduce (uses first element as seed)
    println(nums.scan("") { acc, n -> "$acc$n" })       // [, 1, 12, 123, 1234, 12345]
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.