Kotlin List runningFoldIndexed()
Syntax & Examples


Syntax of List.runningFoldIndexed()

The syntax of List.runningFoldIndexed() extension function is:

fun <T, R> Iterable<T>.runningFoldIndexed( initial: R, operation: (index: Int, acc: R, T) -> R ): List<R>

This runningFoldIndexed() extension function of List 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.



✐ Examples

1 Example

In this example,

  • We create a list named list containing the integers [1, 2, 3, 4, 5].
  • We use the runningFoldIndexed function to accumulate values starting with an initial value of 0.
  • The operation adds the element and its index to the accumulator at each step.
  • The result, which is a list of successive accumulation values, is stored in a variable named result.
  • Finally, we print the result list to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5);
    val result = list.runningFoldIndexed(0) { index, acc, element -> acc + element + index };
    println(result);
}

Output

[0, 1, 4, 9, 16, 25]

2 Example

In this example,

  • We create a list named list containing the strings ['apple', 'banana', 'cherry', 'date', 'elderberry'].
  • We use the runningFoldIndexed function to accumulate values starting with an initial value of an empty string "".
  • The operation concatenates the element and its index to the accumulator at each step.
  • The result, which is a list of successive accumulation values, is stored in a variable named result.
  • Finally, we print the result list to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry", "date", "elderberry");
    val result = list.runningFoldIndexed("") { index, acc, element -> acc + element + index };
    println(result);
}

Output

[, apple0, apple0banana1, apple0banana1cherry2, apple0banana1cherry2date3, apple0banana1cherry2date3elderberry4]

Summary

In this Kotlin tutorial, we learned about runningFoldIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.