reduce

fold 와 비슷하나 reduce 는 초기값을 받지않고 첫번째 인덱스부터 시작한다

public inline fun <S, T: S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S {
    val iterator = this.iterator()
    if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
    var acccumulator: S = iterator.next()
    while (iterator.hasNext()) {
        accumulator = operation(accumulator, iterator.next())
    }
    return accumulator
}


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

Last updated