Kotlin List reduceRightOrNull()
Syntax & Examples
Syntax of List.reduceRightOrNull()
The syntax of List.reduceRightOrNull() extension function is:
fun <S, T : S> List<T>.reduceRightOrNull( operation: (T, acc: S) -> S ): S?This reduceRightOrNull() extension function of List accumulates value starting with the last element and applying operation from right to left to each element and current accumulator value.
✐ Examples
1 Example
In this example,
- We create a list of integers named
listcontaining elements1, 2, 3, 4, 5. - We use the
reduceRightOrNullfunction to accumulate the elements from right to left by adding each element to the accumulator. - The final accumulated value, which is an integer sum, is stored in
result. - We print
resultusingprintln().
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
val result = list.reduceRightOrNull { element, acc -> element + acc }
println(result)
}Output
15
2 Example
In this example,
- We create a list of strings named
listcontaining elements"apple", "banana", "cherry", "date", "elderberry". - We use the
reduceRightOrNullfunction to accumulate the strings from right to left by concatenating them with the accumulator with spaces. - The final accumulated value, which is a string concatenation with spaces, is stored in
result. - We print
resultusingprintln().
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry")
val result = list.reduceRightOrNull { element, acc -> "$element $acc" }
println(result)
}Output
apple banana cherry date elderberry
Summary
In this Kotlin tutorial, we learned about reduceRightOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.