The foldIndexed() extension function in Kotlin accumulates a value starting with an initial value and applying an operation from left to right to the current accumulator value and each element with its index in the set.
The syntax of Set.foldIndexed() extension function is:
fun <T, R> Set<T>.foldIndexed(initial: R, operation: (index: Int, acc: R, T) -> R): R
This foldIndexed() extension function of Set accumulates value starting with initial value and applying operation from left to right to current accumulator value and each element with its index in the original collection.
Parameter | Optional/Required | Description |
---|---|---|
initial | required | The initial value to start the accumulation with. |
operation | required | A function that takes the index, the current accumulator value, and an element, and returns the new accumulator value. |
Set.foldIndexed() returns value of type R
.
Using foldIndexed() to calculate the sum of all elements in a set, each multiplied by its index.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val sum = numbers.foldIndexed(0) { index, acc, num -> acc + index * num }
println(sum)
}
40
Using foldIndexed() to concatenate all strings in a set with their indices into a single string.
For example,
fun main() {
val strings = setOf("a", "b", "c")
val concatenated = strings.foldIndexed("") { index, acc, str -> acc + index + str }
println(concatenated)
}
0a1b2c
Using foldIndexed() to calculate the product of all elements in a set and their indices.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val product = numbers.foldIndexed(1) { index, acc, num -> if (index == 0) acc else acc * index * num }
println(product)
}
240
In this Kotlin tutorial, we learned about foldIndexed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.