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