The fold() extension function in Kotlin accumulates a value starting with an initial value and applying an operation from left to right to the current accumulator value and each element in the set.
The syntax of Set.fold() extension function is:
fun <T, R> Set<T>.fold(initial: R, operation: (acc: R, T) -> R): R
This fold() extension function of Set accumulates value starting with initial value and applying operation from left to right to current accumulator value and each element.
Parameter | Optional/Required | Description |
---|---|---|
initial | required | The initial value to start the accumulation with. |
operation | required | A function that takes the current accumulator value and an element, and returns the new accumulator value. |
Set.fold() returns value of type R
.
Using fold() to calculate the sum of all elements in a set.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val sum = numbers.fold(0) { acc, num -> acc + num }
println(sum)
}
15
Using fold() to concatenate all strings in a set into a single string.
For example,
fun main() {
val strings = setOf("a", "b", "c")
val concatenated = strings.fold("") { acc, str -> acc + str }
println(concatenated)
}
abc
Using fold() to calculate the product of all elements in a set.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val product = numbers.fold(1) { acc, num -> acc * num }
println(product)
}
120
In this Kotlin tutorial, we learned about fold() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.