The scan() 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.
The syntax of Set.scan() extension function is:
fun <T, R> Set<T>.scan(initial: R, operation: (acc: R, T) -> R): List<R>
This scan() 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.
Parameter | Optional/Required | Description |
---|---|---|
initial | required | The initial value for the accumulator. |
operation | required | A function that takes the current accumulator value and an element, and returns the new accumulator value. |
Set.scan() returns value of type List
.
Using scan() to calculate the running sum of elements in a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val runningSums = numbers.scan(0) { acc, num -> acc + num }
println(runningSums)
}
[0, 1, 3, 6, 10, 15]
Using scan() to calculate the running concatenation of strings in a set.
For example,
fun main() {
val strings = setOf("Kotlin", "is", "fun")
val runningConcat = strings.scan("") { acc, str -> "$acc $str".trim() }
println(runningConcat)
}
[, Kotlin, Kotlin is, Kotlin is fun]
Using scan() to calculate the running product of elements in a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4)
val runningProducts = numbers.scan(1) { acc, num -> acc * num }
println(runningProducts)
}
[1, 1, 2, 6, 24]
In this Kotlin tutorial, we learned about scan() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.