fold

  • 초기값과 오퍼레이터를 받는다

  • 왼쪽에서 오른쪽으로 진

public inline fun <T, R> Iterable<T>.fold(initial: R,
operation: (acc: R, T) -> R): R {
    var accumulator = initial
    for (element in this) accumulator = operation(accumulator, element)
    return accumulator
}

val list = listOf(1, 2, 3, 4, 5)
println(list.fold(0, {acc, next -> acc + next}))  // 15

Last updated