Introduction
Fold and reduce help you combine all items in a list into a single result by applying a step-by-step operation.
Fold and reduce help you combine all items in a list into a single result by applying a step-by-step operation.
val result = list.fold(initialValue) { accumulator, item -> // combine accumulator and item } val result = list.reduce { accumulator, item -> // combine accumulator and item }
fold starts with an initial value you provide.
reduce starts with the first item of the list as the initial value.
val numbers = listOf(1, 2, 3) val sum = numbers.fold(0) { acc, n -> acc + n }
val numbers = listOf(1, 2, 3) val product = numbers.reduce { acc, n -> acc * n }
val words = listOf("cat", "elephant", "dog") val longest = words.fold("") { acc, word -> if (word.length > acc.length) word else acc }
This program calculates the sum and product of numbers in a list using fold and reduce.
fun main() { val numbers = listOf(2, 4, 6) val sum = numbers.fold(0) { acc, n -> acc + n } val product = numbers.reduce { acc, n -> acc * n } println("Sum: $sum") println("Product: $product") }
If the list is empty, reduce will throw an error, but fold will return the initial value.
Use fold when you want to provide a safe starting value.
fold combines list items starting from an initial value you give.
reduce combines list items starting from the first item.
Both help turn many items into one result by repeating a simple step.
fold and reduce in Kotlin?fold behaviorfold requires an initial value and then applies the operation starting from that value.reduce behaviorreduce uses the first element of the list as the initial value and then applies the operation to the rest.fold starts with an initial value; reduce starts with the first list item. -> Option Afold on a list listOf(1, 2, 3) to sum all elements starting from 10?fold takes an initial value and a lambda with two parameters: accumulator and current item.fold(10) { acc, item -> acc + item }. Others miss initial value or have wrong lambda syntax.val numbers = listOf(2, 3, 4)
val result = numbers.reduce { acc, item -> acc * item }
println(result)reduce starts with first element (2) as accumulator, then multiplies by next items.reduce:val emptyList = listOf<Int>()
val result = emptyList.reduce { acc, item -> acc + item }
println(result)reduce requires at least one element; empty list causes runtime exception.NoSuchElementException.listOf("a", "b", "c"), which Kotlin expression using fold produces the string "abc-"?Pass the test and this pattern moves unknown