The reduce function

To understand the concept of the reduce function, we'll use addition as an operation. The reduce function adds all elements in the list and returns a result. The difference between the fold and reduce function is that the fold function provides an initial value, fold(0){i,j -> i + j}, but the reduce function does not, reduce { acc, i -> i + acc}.

The reduce function takes a lambda expression that takes two variables and returns a result, as follows:  

var numbers = listOf<Int>(1,2,3,4,5)
var result = numbers.reduce { acc, i -> i + acc}
println("From beginning : add all elements of the list $result")

The reduce function has two different variants.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.39.133