Mastering Kotlin's FoldIndexed: A Comprehensive Guide
In the realm of functional programming, the foldIndexed function is a powerful tool that combines the functionality of both fold and withIndex. It allows you to iterate over a collection, keeping track of the index and the element simultaneously, and perform operations on them. Let's dive into the world of Kotlin's foldIndexed and explore its capabilities.
Understanding FoldIndexed
The foldIndexed function is an extension function in Kotlin that operates on collections. It takes an initial value and a lambda function as parameters. The lambda function takes the index and the element of the collection as arguments and returns a new value. The function iterates over the collection, applying the lambda function to each element and its index, and accumulates the result.
Syntax
The syntax of the foldIndexed function is as follows:

fun Collection.foldIndexed(initial: R, operation: (index: Int, T) -> R): R
Basic Usage
Let's start with a simple example. Suppose we have a list of integers and we want to create a new list that contains the index and the value of each element. We can achieve this using foldIndexed:
val list = listOf(1, 2, 3, 4, 5)
val result = list.foldIndexed(0) { index, value -> Pair(index, value) }
println(result) // prints: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
Performing Operations
The real power of foldIndexed lies in its ability to perform operations on the index and the element. For instance, we can calculate the sum of the indices and the elements in a list:
val sum = list.foldIndexed(0) { index, value -> index + value }
println(sum) // prints: 15
Using FoldIndexed with Mutability
While foldIndexed is typically used with immutable data structures, it can also be used with mutable collections. For example, we can use it to update the values in a mutable list:

val mutableList = mutableListOf(1, 2, 3, 4, 5)
mutableList.foldIndexed(0) { index, value -> mutableList[index] = value * 2 }
println(mutableList) // prints: [2, 4, 6, 8, 10]
FoldIndexed vs Fold
You might be wondering why we would use foldIndexed instead of the simpler fold. The main advantage of foldIndexed is that it provides the index of the current element, which can be useful in certain situations. For example, we can use it to create a mapping of indices to values:
val map = list.foldIndexed(mutableMapOf()) { index, value -> map[index] = value }
println(map) // prints: {0=1, 1=2, 2=3, 3=4, 4=5}
Conclusion
Kotlin's foldIndexed function is a versatile tool that allows you to perform complex operations on collections while keeping track of the index. Whether you're working with immutable data structures or mutable collections, foldIndexed can help you achieve your goals more efficiently. So, the next time you find yourself iterating over a collection and needing the index, consider using foldIndexed. Happy coding!























