Kotlin List reduceRightIndexedOrNull()
Syntax & Examples
Syntax of List.reduceRightIndexedOrNull()
The syntax of List.reduceRightIndexedOrNull() extension function is:
fun <S, T : S> List<T>.reduceRightIndexedOrNull( operation: (index: Int, T, acc: S) -> S ): S?This reduceRightIndexedOrNull() 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 named
listcontaining the integers[1, 2, 3, 4, 5]. - We use the
reduceRightIndexedOrNullfunction to accumulate values starting with the last element. - In the
operation,indexrepresents the index of the current element,elementrepresents the current element, andaccrepresents the accumulator value. - If the index is even, we add the element to the accumulator; otherwise, we keep the accumulator unchanged.
- Finally, we print the result to standard output using the
printlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val result = list.reduceRightIndexedOrNull { index, element, acc -> if (index % 2 == 0) element + acc else acc };
println(result);
}Output
9
2 Example
In this example,
- We create a list named
listcontaining the strings['apple', 'banana', 'cherry', 'date', 'elderberry']. - We use the
reduceRightIndexedOrNullfunction to accumulate values starting with the last element. - In the
operation,indexrepresents the index of the current element,elementrepresents the current element, andaccrepresents the accumulator value. - If the index is greater than 0, we add the length of the element to the accumulator; otherwise, we keep the accumulator unchanged.
- Finally, we print the result to standard output using the
printlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val result = list.reduceRightIndexedOrNull { index, element, acc -> if (index > 0) acc + element.length else acc };
println(result);
}Output
elderberry466
Summary
In this Kotlin tutorial, we learned about reduceRightIndexedOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.