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