The reduceOrNull() extension function in Kotlin accumulates a value starting with the first element and applying an operation from left to right to the current accumulator value and each element. If the collection is empty, it returns null.
The syntax of Set.reduceOrNull() extension function is:
fun <S, T : S> Set<T>.reduceOrNull(operation: (acc: S, T) -> S): S?
This reduceOrNull() extension function of Set accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element.
Parameter | Optional/Required | Description |
---|---|---|
operation | required | A function that takes the current accumulator value and an element, and returns the new accumulator value. |
Set.reduceOrNull() returns value of type S?
.
Using reduceOrNull() to sum the elements in a set of integers, or return null if the set is empty.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val sum = numbers.reduceOrNull { acc, num -> acc + num }
println(sum)
}
15
Using reduceOrNull() to concatenate the strings in a set, or return null if the set is empty.
For example,
fun main() {
val strings = setOf("Kotlin", "is", "fun")
val result = strings.reduceOrNull { acc, str -> "$acc $str" }
println(result)
}
Kotlin is fun
Using reduceOrNull() to calculate the product of the elements in a set of integers, or return null if the set is empty.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4)
val product = numbers.reduceOrNull { acc, num -> acc * num }
println(product)
}
24
Using reduceOrNull() to handle an empty set and return null.
For example,
fun main() {
val emptySet = emptySet<Int>()
val result = emptySet.reduceOrNull { acc, num -> acc + num }
println(result)
}
null
In this Kotlin tutorial, we learned about reduceOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.