List — reduce() / fold()
Kotlin's reduce() folds a list without an initial value. fold() folds a list with a specified initial value. Use these functions when you want to combine all elements of a list into a single value — such as a sum, product, or concatenated string.
Syntax
val numbers = listOf(1, 2, 3, 4, 5)
// reduce — no initial value (the first element is used as the initial value)
val sum = numbers.reduce { acc, n -> acc + n } // 15
// fold — with an initial value (safe even for empty lists)
val sumFold = numbers.fold(0) { acc, n -> acc + n } // 15
val product = numbers.fold(1) { acc, n -> acc * n } // 120
// Folds from the right.
val right = numbers.foldRight(0) { n, acc -> n + acc } // 15
Method List
| Method | Description |
|---|---|
| list.reduce { acc, v -> } | Folds from the left. The first element is used as the initial value. Throws an exception on an empty list. |
| list.reduceOrNull { acc, v -> } | Same as reduce, but returns null for an empty list. |
| list.reduceRight { v, acc -> } | Folds from the right (note the argument order). |
| list.fold(initial) { acc, v -> } | Folds from the left with a specified initial value. |
| list.foldRight(initial) { v, acc -> } | Folds from the right with a specified initial value (note the argument order). |
| list.runningFold(initial) { acc, v -> } | Returns a list of intermediate results at each step (useful for prefix sums, etc.). |
| list.runningReduce { acc, v -> } | Returns a list of intermediate results from reduce. |
Sample Code
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// reduce — sum (first element is the initial value)
val sum = numbers.reduce { acc, n -> acc + n }
println("Sum: $sum") // 15
// fold — specify an initial value (safe even for empty lists)
val product = numbers.fold(1) { acc, n -> acc * n }
println("Product: $product") // 120
// Concatenate strings with fold.
val words = listOf("Kotlin", "is", "awesome")
val sentence = words.fold("") { acc, w -> if (acc.isEmpty()) w else "$acc $w" }
println("Sentence: $sentence") // Kotlin is awesome
println()
// Complex fold (build a map)
data class Item(val name: String, val price: Int, val qty: Int)
val cart = listOf(
Item("Apple", 150, 2),
Item("Banana", 100, 3),
Item("Orange", 200, 1)
)
val total = cart.fold(0) { acc, item -> acc + item.price * item.qty }
println("Total: $total") // 800
println()
// runningFold — cumulative sum (shows intermediate values at each step)
val cumulative = numbers.runningFold(0) { acc, n -> acc + n }
println("Cumulative sum: $cumulative") // [0, 1, 3, 6, 10, 15]
// runningReduce — running maximum
val runMax = numbers.map { it * it }.runningReduce { acc, n -> maxOf(acc, n) }
println("Running max: $runMax")
println()
// foldRight — processes from the right (note the argument order)
val reversed = listOf("a", "b", "c").foldRight(mutableListOf()) { elem: String, acc: MutableList<String> ->
acc.add(0, elem)
acc
}
println("Reversed: $reversed")
// Safe handling of empty lists
val empty = emptyList<Int>()
println("reduceOrNull: ${empty.reduceOrNull { acc, n -> acc + n }}") // null
println("fold: ${empty.fold(0) { acc, n -> acc + n }}") // 0
}
Notes
Because reduce() throws an exception on an empty list, use fold() or reduceOrNull() when the list may be empty. fold() is more versatile — by changing the type of the initial value, you can transform a list of numbers into a different type, such as a map.
For simple operations like summing or finding the maximum, dedicated shorthands such as sum() and max() are more concise. Use fold() for complex aggregation logic.
For flattening, see List — flatMap() / flatten(). For grouping, see List — groupBy() / partition().
If you find any errors or copyright issues, please contact us.