runningFoldIndexed

inline fun <R> CharSequence.runningFoldIndexed(initial: R, operation: (index: Int, acc: R, Char) -> R): List<R>(source)

Returns a list containing successive accumulation values generated by applying operation from left to right to each character, its index in the original char 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 list.

Since Kotlin

1.4

Parameters

operation

function that takes the index of a character, current accumulator value and the character itself, and calculates the next accumulator value.

Samples

import kotlin.test.*

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

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