0
0
Kotlinprogramming~5 mins

Fold and reduce operations in Kotlin

Choose your learning style9 modes available
Introduction

Fold and reduce help you combine all items in a list into a single result by applying a step-by-step operation.

When you want to add all numbers in a list to get their total.
When you want to multiply all values in a list to get a product.
When you want to find the longest word in a list of words.
When you want to combine strings from a list into one sentence.
Syntax
Kotlin
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.

Examples
Adds all numbers starting from 0, result is 6.
Kotlin
val numbers = listOf(1, 2, 3)
val sum = numbers.fold(0) { acc, n -> acc + n }
Multiplies all numbers starting from first item, result is 6.
Kotlin
val numbers = listOf(1, 2, 3)
val product = numbers.reduce { acc, n -> acc * n }
Finds the longest word by comparing lengths.
Kotlin
val words = listOf("cat", "elephant", "dog")
val longest = words.fold("") { acc, word -> if (word.length > acc.length) word else acc }
Sample Program

This program calculates the sum and product of numbers in a list using fold and reduce.

Kotlin
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")
}
OutputSuccess
Important Notes

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.

Summary

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.