Kotlin List reduceRightIndexed()
Syntax & Examples


Syntax of List.reduceRightIndexed()

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

fun <S, T : S> List<T>.reduceRightIndexed( operation: (index: Int, T, acc: S) -> S ): S

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



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We use the reduceRightIndexed function to accumulate the elements by subtracting the product of the element and its index from the accumulator, starting from the right.
  • The final accumulated value, which is an integer calculation, is stored in result.
  • We print result using println().

Kotlin Program

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

Output

-15

2 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry", "date", "elderberry".
  • We use the reduceRightIndexed function to accumulate the strings by concatenating them with the accumulator from the right with a space.
  • The final accumulated value, which is a string concatenation with spaces, is stored in result.
  • We print result using println().

Kotlin Program

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

Output

apple banana cherry date elderberry

Summary

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