Kotlin List reduceOrNull()
Syntax & Examples
Syntax of List.reduceOrNull()
The syntax of List.reduceOrNull() extension function is:
fun <S, T : S> Iterable<T>.reduceOrNull( operation: (acc: S, T) -> S ): S?This reduceOrNull() 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.
✐ Examples
1 Example
In this example,
- We create a list of integers named listcontaining elements1, 2, 3, 4, 5.
- We use the reduceOrNullfunction to accumulate the elements by adding them together from left to right.
- 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.reduceOrNull { acc, element -> acc + element }
    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 reduceOrNullfunction to accumulate the strings by concatenating them with a hyphen from left to right.
- The final accumulated value, which is a string concatenation with colons, 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.reduceOrNull { acc, element -> "$acc - $element" }
    println(result)
}Output
apple - banana - cherry - date - elderberry
Summary
In this Kotlin tutorial, we learned about reduceOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.
