The reduceIndexed() 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.
The syntax of Set.reduceIndexed() extension function is:
fun <S, T : S> Set<T>.reduceIndexed(operation: (index: Int, acc: S, T) -> S): S
This reduceIndexed() 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.reduceIndexed() returns value of type S
.
Using reduceIndexed() to sum the elements in a set of integers while considering the index.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val sum = numbers.reduceIndexed { index, acc, num -> acc + num + index }
println(sum)
}
25
Using reduceIndexed() to concatenate the strings in a set while considering the index.
For example,
fun main() {
val strings = setOf("Kotlin", "is", "fun")
val result = strings.reduceIndexed { index, acc, str -> "$acc $index:$str" }
println(result)
}
Kotlin 1:is 2:fun
Using reduceIndexed() to calculate the product of the elements in a set of integers while considering the index.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4)
val product = numbers.reduceIndexed { index, acc, num -> acc * (num + index) }
println(product)
}
288
In this Kotlin tutorial, we learned about reduceIndexed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.