Kotlin List reduceIndexed()
Syntax & Examples


Syntax of List.reduceIndexed()

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

fun <S, T : S> Iterable<T>.reduceIndexed( operation: (index: Int, acc: S, T) -> S ): S

This reduceIndexed() extension function of List accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element with its index in the original collection.



✐ Examples

1 Example

In this example,

  • We create a list named list containing the integers [1, 2, 3, 4, 5].
  • We use the reduceIndexed function to accumulate values starting with the first element.
  • In the operation, index represents the index of the current element, acc represents the accumulator value, and element represents the current element.
  • We multiply the current element by its index and add it to the accumulator.
  • Finally, we print the result 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.reduceIndexed { index, acc, element -> acc + index * element };
    println(result);
}

Output

41

2 Example

In this example,

  • We create a list named list containing the strings ['apple', 'banana', 'cherry', 'date', 'elderberry'].
  • We use the reduceIndexed function to accumulate values starting with the first element.
  • In the operation, index represents the index of the current element, acc represents the accumulator value, and element represents the current element.
  • We concatenate the current element with its index and add it to the accumulator.
  • Finally, we print the result 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.reduceIndexed { index, acc, element -> acc + element + index };
    println(result);
}

Output

applebanana1cherry2date3elderberry4

Summary

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