Kotlin List reduceIndexedOrNull()
Syntax & Examples
Syntax of List.reduceIndexedOrNull()
The syntax of List.reduceIndexedOrNull() extension function is:
fun <S, T : S> Iterable<T>.reduceIndexedOrNull( operation: (index: Int, acc: S, T) -> S ): S?
This reduceIndexedOrNull() 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 of strings named
list
containing elements"apple", "banana", "cherry", "date", "elderberry"
. - We use the
reduceIndexedOrNull
function to accumulate the strings by concatenating them with their indices and a colon from left to right. - The final accumulated value, which is a string combining strings, their indices, and colons, is stored in
result
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry")
val result = list.reduceIndexedOrNull { index, acc, element -> "$acc[$index]: $element" }
println(result)
}
Output
apple[1]: banana[2]: cherry[3]: date[4]: elderberry
2 Example
In this example,
- We create a list of integers named
list
containing elements1, 2, 3, 4, 5
. - We use the
reduceIndexedOrNull
function to accumulate the elements by adding them together with their indices from left to right. - The final accumulated value, which is a string combining elements and their indices, is stored in
result
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
val result = list.reduceIndexedOrNull { index, acc, element -> acc + element + index }
println(result)
}
Output
25
Summary
In this Kotlin tutorial, we learned about reduceIndexedOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.