Kotlin Set fold()
Syntax & Examples
Set.fold() extension function
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.
Syntax of Set.fold()
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.
Parameters
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. |
Return Type
Set.fold() returns value of type R
.
✐ Examples
1 Summing elements of a set
Using fold() to calculate the sum of all elements in a set.
For example,
- Create a set of integers.
- Define an initial value of 0.
- Define an operation function that adds each element to the accumulator.
- Use fold() to calculate the sum of all elements in the set.
- Print the resulting sum.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val sum = numbers.fold(0) { acc, num -> acc + num }
println(sum)
}
Output
15
2 Concatenating strings in a set
Using fold() to concatenate all strings in a set into a single string.
For example,
- Create a set of strings.
- Define an initial value of an empty string.
- Define an operation function that concatenates each string to the accumulator.
- Use fold() to concatenate all strings in the set.
- Print the resulting string.
Kotlin Program
fun main() {
val strings = setOf("a", "b", "c")
val concatenated = strings.fold("") { acc, str -> acc + str }
println(concatenated)
}
Output
abc
3 Calculating the product of elements in a set
Using fold() to calculate the product of all elements in a set.
For example,
- Create a set of integers.
- Define an initial value of 1.
- Define an operation function that multiplies each element with the accumulator.
- Use fold() to calculate the product of all elements in the set.
- Print the resulting product.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val product = numbers.fold(1) { acc, num -> acc * num }
println(product)
}
Output
120
Summary
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.