Kotlin List foldIndexed()
Syntax & Examples
Syntax of List.foldIndexed()
The syntax of List.foldIndexed() extension function is:
fun <T, R> Iterable<T>.foldIndexed( initial: R, operation: (index: Int, acc: R, T) -> R ): R
This foldIndexed() extension function of List 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.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list1
. - We use the
foldIndexed()
function onlist1
starting with an initial value of 0. - The operation in
foldIndexed()
adds the value of each element with its index to the accumulator. - The final result is printed to standard output using the
println
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val result = list1.foldIndexed(0) { index, acc, value -> acc + value + index }
println(result)
}
Output
25
2 Example
In this example,
- We create a list of characters named
list2
. - We use the
foldIndexed()
function onlist2
starting with an initial value of an empty string. - The operation in
foldIndexed()
concatenates each character with its index to the accumulator. - The final result is printed to standard output using the
println
statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf('a', 'b', 'c')
val result = list2.foldIndexed("", { index, acc, value -> acc + value + index })
println(result)
}
Output
a0b1c2
3 Example
In this example,
- We create a list of strings named
list3
. - We use the
foldIndexed()
function onlist3
starting with an initial value of an empty string. - The operation in
foldIndexed()
concatenates each string with its index to the accumulator. - The final result is printed to standard output using the
println
statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "cherry")
val result = list3.foldIndexed("", { index, acc, value -> acc + value + index })
println(result)
}
Output
apple0banana1cherry2
Summary
In this Kotlin tutorial, we learned about foldIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.