reduceRight
public inline fun <S, T: S> List<T>.reduceRight(operation: (T, acc: S) -> S): S {
val iterator = listIterator(size)
if (!iterator.hasPrevious)
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
return accumulator
}
val list = listOf(1, 2, 3, 4, 5)
println(list.reduceRight{ before, acc -> before + acc }) // 15
Last updated