fold
takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters.listOf(1, 2, 3).fold(0) { sum, element -> sum + element }
The first call to the lambda will be with parameters
0
and1
.Having the ability to pass in an initial value is useful if you have to provide some sort of default value or parameter for your operation.
reduce
doesn’t take an initial value, but instead starts with the first element of the collection as the accumulator (calledsum
in the following example)listOf(1, 2, 3).reduce { sum, element -> sum + element }
The first call to the lambda here will be with parameters
1
and2
.