Kotlin Set runningFold()
Syntax & Examples


Set.runningFold() extension function

The runningFold() extension function in Kotlin returns a list containing successive accumulation values generated by applying an operation from left to right to each element and the current accumulator value that starts with an initial value.


Syntax of Set.runningFold()

The syntax of Set.runningFold() extension function is:

fun <T, R> Set<T>.runningFold(initial: R, operation: (acc: R, T) -> R): List<R>

This runningFold() extension function of Set returns a list containing successive accumulation values generated by applying operation from left to right to each element and current accumulator value that starts with initial value.

Parameters

ParameterOptional/RequiredDescription
initialrequiredThe initial value for the accumulator.
operationrequiredA function that takes the current accumulator value and an element, and returns the new accumulator value.

Return Type

Set.runningFold() returns value of type List.



✐ Examples

1 Running sum of elements in a set of integers

Using runningFold() to calculate the running sum of elements in a set of integers.

For example,

  1. Create a set of integers.
  2. Use runningFold() with an initial value of 0 and an operation that adds each element to the accumulator.
  3. Print the resulting list of running sums.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val runningSums = numbers.runningFold(0) { acc, num -> acc + num }
    println(runningSums)
}

Output

[0, 1, 3, 6, 10, 15]

2 Running concatenation of strings in a set

Using runningFold() to calculate the running concatenation of strings in a set.

For example,

  1. Create a set of strings.
  2. Use runningFold() with an initial value of an empty string and an operation that concatenates each string to the accumulator.
  3. Print the resulting list of running concatenations.

Kotlin Program

fun main() {
    val strings = setOf("Kotlin", "is", "fun")
    val runningConcat = strings.runningFold("") { acc, str -> "$acc $str".trim() }
    println(runningConcat)
}

Output

[, Kotlin, Kotlin is, Kotlin is fun]

3 Running product of elements in a set of integers

Using runningFold() to calculate the running product of elements in a set of integers.

For example,

  1. Create a set of integers.
  2. Use runningFold() with an initial value of 1 and an operation that multiplies each element to the accumulator.
  3. Print the resulting list of running products.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4)
    val runningProducts = numbers.runningFold(1) { acc, num -> acc * num }
    println(runningProducts)
}

Output

[1, 1, 2, 6, 24]

Summary

In this Kotlin tutorial, we learned about runningFold() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.