The fold function in Kotlin is a powerful and versatile higher-order extension function available on collections. It allows you to accumulate a single value from a collection by iteratively applying an operation to each element, carrying forward an intermediate result.
Let's break down the function signature you provided:
kotlin
fun <T, R> Collection<T>.fold(
initial: R,
combine: (acc: R, nextElement: T) -> R
): R
Components of the fold Function
Type Parameters:
<T, R>:
T is the type of elements in the collection.
R is the type of the result after folding the collection.
Receiver:
Collection<T>: fold is an extension function on any Collection containing elements of type T.
Parameters:
initial: R: The initial value of the accumulator. This is the starting point for the fold operation.
combine: (acc: R, nextElement: T) -> R: A lambda function that defines how to combine the current accumulator (acc) with the next element in the collection (nextElement) to produce a new accumulator value.
Return Type:
R: The final accumulated value after processing all elements in the collection.
How fold Works
The fold function processes the collection from left to right (i.e., from the first element to the last). It starts with the initial value as the accumulator. For each element in the collection, it applies the combine function, updating the accumulator with the result. After processing all elements, it returns the final accumulator value.
Step-by-Step Example
Let's illustrate how fold works with a concrete example.
Example 1: Summing a List of Integers
Suppose you have a list of integers and you want to calculate their sum.
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.fold(0) { acc, number ->
acc + number
}
println(sum) // Output: 15
Explanation:
Initial Accumulator (acc): Starts at 0.
First Element (1): 0 + 1 = 1
Second Element (2): 1 + 2 = 3
Third Element (3): 3 + 3 = 6
Fourth Element (4): 6 + 4 = 10
Fifth Element (5): 10 + 5 = 15
Final Result: 15
Example 2: Creating a String from a List
Suppose you have a list of strings and want to concatenate them into a single string, separated by commas.
kotlin
val words = listOf("Kotlin", "is", "fun")
val sentence = words.fold("") { acc, word ->
if (acc.isEmpty()) word else "$acc, $word"
}
println(sentence) // Output: Kotlin, is, fun
Explanation:
Initial Accumulator (acc): Starts as an empty string "".
First Element ("Kotlin"): Since acc is empty, set acc to "Kotlin".
Second Element ("is"): Concatenate with a comma: "Kotlin, is".
Third Element ("fun"): Concatenate with a comma: "Kotlin, is, fun".
Final Result: "Kotlin, is, fun"
Use Cases for fold
Aggregation: Summing numbers, finding products, concatenating strings, etc.
Transformation: Building complex objects from collection elements.
Stateful Operations: Applying operations that maintain a state across elements.
Comparison with Related Functions
Kotlin provides several similar functions for processing collections. Understanding how fold differs from them can help you choose the right tool for your task.
reduce Function:
kotlin
fun <S> Iterable<S>.reduce(operation: (acc: S, S) -> S): S
Difference from fold:
reduce does not take an explicit initial value. Instead, it uses the first element of the collection as the initial accumulator and starts folding from the second element.
Throws an exception if the collection is empty.
Use Case: When you’re certain the collection is non-empty and you want to use the first element as the starting point.
Example:
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.reduce { acc, number -> acc + number }
println(sum) // Output: 15
foldRight Function:
kotlin
fun <T, R> Iterable<T>.foldRight(
initial: R,
operation: (T, acc: R) -> R
): R
Difference from fold:
Processes the collection from right to left (i.e., from the last element to the first).
Use Case: When the order of processing matters, especially for operations that are not commutative.
Example:
kotlin
val words = listOf("Kotlin", "is", "fun")
val sentence = words.foldRight("") { word, acc ->
if (acc.isEmpty()) word else "$word, $acc"
}
println(sentence) // Output: Kotlin, is, fun
foldIndexed Function:
kotlin
fun <T, R> Iterable<T>.foldIndexed(
initial: R,
operation: (index: Int, acc: R, T) -> R
): R
Difference from fold:
Provides the index of each element during the folding operation.
When to Use fold
Use fold when you need to:
Traverse a collection and accumulate a result.
Start with a specific initial value.
Apply a transformation that depends on both the current accumulator and the current element.
Additional Considerations
Immutability:fold does not mutate the original collection or the accumulator. Instead, it returns a new accumulated value.
Generic: The function is generic over both the element type (T) and the result type (R), making it highly flexible for various use cases.
Summary
The fold function is a versatile tool in Kotlin for reducing a collection to a single value by applying a specified operation sequentially to each element, carrying forward an accumulator. Its ability to start with an initial value and be generic over input and output types makes it suitable for a wide range of operations, from simple summations to complex transformations.
Additional Example: Building a Map from a List
Suppose you have a list of strings and want to create a map that counts the occurrences of each string.
kotlin
val words = listOf("apple", "banana", "apple", "orange", "banana", "apple")
val wordCount = words.fold(mutableMapOf<String, Int>()) { acc, word ->
acc[word] = acc.getOrDefault(word, 0) + 1
acc
}
println(wordCount) // Output: {apple=3, banana=2, orange=1}
Explanation:
Initial Accumulator (acc): Starts as an empty mutable map.
For each word, increment its count in the map.
Final Result: A map with each word as a key and its count as the value.
This example demonstrates how fold can be used to build more complex data structures from a collection.