Kotlin Set foldIndexed()
Syntax & Examples
Set.foldIndexed() extension function
The foldIndexed() 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 with its index in the set.
Syntax of Set.foldIndexed()
The syntax of Set.foldIndexed() extension function is:
fun <T, R> Set<T>.foldIndexed(initial: R, operation: (index: Int, acc: R, T) -> R): R
This foldIndexed() extension function of Set accumulates value starting with initial value and applying operation from left to right to current accumulator value and each element with its index in the original collection.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
initial | required | The initial value to start the accumulation with. |
operation | required | A function that takes the index, the current accumulator value, and an element, and returns the new accumulator value. |
Return Type
Set.foldIndexed() returns value of type R
.
✐ Examples
1 Summing elements with their indices
Using foldIndexed() to calculate the sum of all elements in a set, each multiplied by its index.
For example,
- Create a set of integers.
- Define an initial value of 0.
- Define an operation function that adds the product of each element and its index to the accumulator.
- Use foldIndexed() to calculate the sum.
- Print the resulting sum.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val sum = numbers.foldIndexed(0) { index, acc, num -> acc + index * num }
println(sum)
}
Output
40
2 Concatenating strings with their indices
Using foldIndexed() to concatenate all strings in a set with their indices 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 and its index to the accumulator.
- Use foldIndexed() to concatenate all strings in the set.
- Print the resulting string.
Kotlin Program
fun main() {
val strings = setOf("a", "b", "c")
val concatenated = strings.foldIndexed("") { index, acc, str -> acc + index + str }
println(concatenated)
}
Output
0a1b2c
3 Calculating the product of elements and their indices
Using foldIndexed() to calculate the product of all elements in a set and their indices.
For example,
- Create a set of integers.
- Define an initial value of 1.
- Define an operation function that multiplies the product of each element and its index with the accumulator.
- Use foldIndexed() to calculate the product.
- Print the resulting product.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val product = numbers.foldIndexed(1) { index, acc, num -> if (index == 0) acc else acc * index * num }
println(product)
}
Output
240
Summary
In this Kotlin tutorial, we learned about foldIndexed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.