Kotlin Tutorials

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

ParameterOptional/RequiredDescription
initialrequiredThe initial value to start the accumulation with.
operationrequiredA 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,

  1. Create a set of integers.
  2. Define an initial value of 0.
  3. Define an operation function that adds each element to the accumulator.
  4. Use fold() to calculate the sum of all elements in the set.
  5. 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,

  1. Create a set of strings.
  2. Define an initial value of an empty string.
  3. Define an operation function that concatenates each string to the accumulator.
  4. Use fold() to concatenate all strings in the set.
  5. 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,

  1. Create a set of integers.
  2. Define an initial value of 1.
  3. Define an operation function that multiplies each element with the accumulator.
  4. Use fold() to calculate the product of all elements in the set.
  5. 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.