Kotlin List reduce(), reduceIndexed(), reduceRight(), reduceRightIndexed() methods example
In the tutorial, Grokonez will show you how to work with Kotlin List methods reduce(), reduceIndexed(), reduceRight(), reduceRightIndexed().
I. Kotlin List reduce methods
1. reduce()
reduce() accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element.
Method signature:
public inline fun Iterable.reduce(operation: (acc: S, T) -> S): S
Practice:
val intList = listOf(1, 2, 3, 4, 5, 6)
var intResult = intList.reduce { acc, it ->
println("acc = $acc, it = $it")
acc + it }
println(intResult)
/*
acc = 1, it = 2
acc = 3, it = 3
acc = 6, it = 4
acc = 10, it = 5
acc = 15, it = 6
21
*/
More at:
Kotlin List reduce(), reduceIndexed(), reduceRight(), reduceRightIndexed() methods example
Top comments (0)