runningFold所在位置是kotlin.collections.runningFold,其相关用法介绍如下。

用法:

inline fun <T, R> Array<out T>.runningFold(
    initial: R, 
    operation: (acc: R, T) -> R
): List<R>
inline fun <R> ByteArray.runningFold(
    initial: R, 
    operation: (acc: R, Byte) -> R
): List<R>
inline fun <R> ShortArray.runningFold(
    initial: R, 
    operation: (acc: R, Short) -> R
): List<R>
inline fun <R> IntArray.runningFold(
    initial: R, 
    operation: (acc: R, Int) -> R
): List<R>
inline fun <R> LongArray.runningFold(
    initial: R, 
    operation: (acc: R, Long) -> R
): List<R>
inline fun <R> FloatArray.runningFold(
    initial: R, 
    operation: (acc: R, Float) -> R
): List<R>
inline fun <R> DoubleArray.runningFold(
    initial: R, 
    operation: (acc: R, Double) -> R
): List<R>
inline fun <R> BooleanArray.runningFold(
    initial: R, 
    operation: (acc: R, Boolean) -> R
): List<R>
inline fun <R> CharArray.runningFold(
    initial: R, 
    operation: (acc: R, Char) -> R
): List<R>
inline fun <T, R> Iterable<T>.runningFold(
    initial: R, 
    operation: (acc: R, T) -> R
): List<R>
@ExperimentalUnsignedTypes inline fun <R> UIntArray.runningFold(
    initial: R, 
    operation: (acc: R, UInt) -> R
): List<R>
@ExperimentalUnsignedTypes inline fun <R> ULongArray.runningFold(
    initial: R, 
    operation: (acc: R, ULong) -> R
): List<R>
@ExperimentalUnsignedTypes inline fun <R> UByteArray.runningFold(
    initial: R, 
    operation: (acc: R, UByte) -> R
): List<R>
@ExperimentalUnsignedTypes inline fun <R> UShortArray.runningFold(
    initial: R, 
    operation: (acc: R, UShort) -> R
): List<R>

返回一个列表,其中包含通过从左到右将operation 应用于每个元素和以initial 值开头的当前累加器值生成的连续累加值。

请注意,传递给operation 函数的acc 值不应被改变;否则会影响结果列表中的前一个值。

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//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
}

输出:

[s, sa, sab, sabc, sabcd]
[s, sa0, sa0b1, sa0b1c2, sa0b1c2d3]
[s]

参数

operation- 获取当前累加器值和一个元素并计算下一个累加器值的函数。