The runningFoldIndexed() extension function in Kotlin returns a list containing successive accumulation values generated by applying an operation from left to right to each element, its index in the original collection, and the current accumulator value that starts with an initial value.
The syntax of Set.runningFoldIndexed() extension function is:
fun <T, R> Set<T>.runningFoldIndexed(initial: R, operation: (index: Int, acc: R, T) -> R): List<R>
This runningFoldIndexed() extension function of Set returns a list containing successive accumulation values generated by applying operation from left to right to each element, its index in the original collection and current accumulator value that starts with initial value.
Parameter | Optional/Required | Description |
---|---|---|
initial | required | The initial value for the accumulator. |
operation | required | A function that takes the current index, the current accumulator value, and an element, and returns the new accumulator value. |
Set.runningFoldIndexed() returns value of type List
.
Using runningFoldIndexed() to calculate the running sum of elements in a set of integers while considering the index.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val runningSums = numbers.runningFoldIndexed(0) { index, acc, num -> acc + num + index }
println(runningSums)
}
[0, 1, 4, 9, 16, 25]
Using runningFoldIndexed() to calculate the running concatenation of strings in a set while considering the index.
For example,
fun main() {
val strings = setOf("Kotlin", "is", "fun")
val runningConcat = strings.runningFoldIndexed("") { index, acc, str -> "$acc $index:$str".trim() }
println(runningConcat)
}
[, 0:Kotlin, 0:Kotlin 1:is, 0:Kotlin 1:is 2:fun]
Using runningFoldIndexed() to calculate the running product of elements in a set of integers while considering the index.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4)
val runningProducts = numbers.runningFoldIndexed(1) { index, acc, num -> acc * (num + index) }
println(runningProducts)
}
[1, 1, 4, 18, 90]
In this Kotlin tutorial, we learned about runningFoldIndexed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.