Kotlin List runningReduceIndexed()
Syntax & Examples
Syntax of List.runningReduceIndexed()
The syntax of List.runningReduceIndexed() extension function is:
fun <S, T : S> Iterable<T>.runningReduceIndexed( operation: (index: Int, acc: S, T) -> S ): List<S>
This runningReduceIndexed() 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 the first element of this collection.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the integers[1, 2, 3, 4, 5]
. - We use the
runningReduceIndexed
function to accumulate values starting with the first element of the list. - 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.runningReduceIndexed { index, acc, element -> acc + element + index };
println(result);
}
Output
[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
runningReduceIndexed
function to accumulate values starting with the first element of the list. - 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("apple", "banana", "cherry", "date", "elderberry");
val result = list.runningReduceIndexed { index, acc, element -> acc + element + index };
println(result);
}
Output
[apple, applebanana1, applebanana1cherry2, applebanana1cherry2date3, applebanana1cherry2date3elderberry4]
Summary
In this Kotlin tutorial, we learned about runningReduceIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.