Kotlin List scanIndexed()
Syntax & Examples


Syntax of List.scanIndexed()

The syntax of List.scanIndexed() extension function is:

fun <T, R> Iterable<T>.scanIndexed( initial: R, operation: (index: Int, acc: R, T) -> R ): List<R>

This scanIndexed() extension function of List returns a list containing successive accumulation values generated by applying operation from left to right to each element, its index in the original collection and current accumulator value that starts with initial value.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We use the scanIndexed function to accumulate values by multiplying the element with its index and adding to the accumulator, starting with an initial value of 0.
  • The resulting list of accumulated values is stored in result.
  • We print result using println().

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    val result = list.scanIndexed(0) { index, acc, element -> acc + index * element }
    println(result)
}

Output

[0, 0, 2, 8, 20, 40]

2 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry".
  • We use the scanIndexed function to accumulate values by adding the length of the element and the index to the accumulator, starting with an initial value of an empty string "".
  • The resulting list of accumulated strings is stored in result.
  • We print result using println().

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry")
    val result = list.scanIndexed("") { index, acc, element -> acc + element.length + index }
    println(result)
}

Output

[, 50, 5061, 506162]

Summary

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