scanIndexed

Common
JVM
JS
Native
1.3
@ExperimentalStdlibApi fun <T, R> Sequence<T>.scanIndexed(
    initial: R,
    operation: (index: Int, acc: R, T) -> R
): Sequence<R>

Returns a sequence containing successive accumulation values generated by applying operation from left to right to each element, its index in the original sequence and current accumulator value that starts with initial value.

Note that acc value passed to operation function should not be mutated; otherwise it would affect the previous value in resulting sequence. The initial value should also be immutable (or should not be mutated) as it may be passed to operation function later because of sequence's lazy nature.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val strings = listOf("a", "b", "c", "d")
println(strings.scan("s") { acc, string -> acc + string }) // [s, sa, sab, sabc, sabcd]
println(strings.scanIndexed("s") { index, acc, string -> acc + string + index }) // [s, sa0, sa0b1, sa0b1c2, sa0b1c2d3]

println(emptyList<String>().scan("s") { _, _ -> "X" }) // [s]
//sampleEnd
}

Parameters

operation -

function that takes the index of an element, current accumulator value and the element itself, and calculates the next accumulator value.

The operation is intermediate and stateless.