Kotlin List foldRightIndexed()
Syntax & Examples
Syntax of List.foldRightIndexed()
The syntax of List.foldRightIndexed() extension function is:
fun <T, R> List<T>.foldRightIndexed( initial: R, operation: (index: Int, T, acc: R) -> R ): R
This foldRightIndexed() extension function of List accumulates value starting with initial value and applying operation from right to left to each element with its index in the original list and current accumulator value.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list1
. - We use the
foldRightIndexed()
function onlist1
starting with an initial value of 0. - The operation in
foldRightIndexed()
adds the value of each element with its index to the accumulator from right to left. - 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.foldRightIndexed(0) { index, value, acc -> acc + value + index }
println(result)
}
Output
25
2 Example
In this example,
- We create a list of characters named
list2
. - We use the
foldRightIndexed()
function onlist2
starting with an initial value of an empty string. - The operation in
foldRightIndexed()
concatenates each character with its index to the accumulator from right to left. - 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.foldRightIndexed("", { index, value, acc -> acc + value + index })
println(result)
}
Output
c2b1a0
3 Example
In this example,
- We create a list of strings named
list3
. - We use the
foldRightIndexed()
function onlist3
starting with an initial value of an empty string. - The operation in
foldRightIndexed()
concatenates each string with its index to the accumulator from right to left. - 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.foldRightIndexed("", { index, value, acc -> acc + value + index })
println(result)
}
Output
cherry2banana1apple0
Summary
In this Kotlin tutorial, we learned about foldRightIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.