W3cubDocs

/Kotlin

scan

Platform and version requirements: JVM (1.4), JS (1.4), Native (1.4)
inline fun <R> CharSequence.scan(
    initial: R, 
    operation: (acc: R, Char) -> R
): List<R>

Returns a list containing successive accumulation values generated by applying operation from left to right to each character 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.

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 current accumulator value and a character, and calculates the next accumulator value.

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/scan.html