`fold()`

combines all elements of a list in order to produce a single result.

A common puzzle is to implement an operation such as `sum()`

or `reverse()`

using `fold()`

. Here, `fold()`

sums a sequence:

```
// FoldingLists/SumViaFold.kt
import atomictest.eq
fun main(args: Array<String>) {
val list = listOf(1, 10, 100, 1000)
list.fold(0) {
sum, n -> sum + n
} eq 1111
}
```

`fold()`

takes the initial value (its argument) and successively applies the operation (expressed here as a lambda) to combine the current accumulated value with each element. In this example, the initial value is `0`

. `fold()`

first adds `0`

and `1`

to get `1`

. That becomes the `sum`

, which is added to the `10`

to get `11`

, which becomes the new `sum`

. The operation is repeated for two more elements: `100`

and `1000`

. This produces `111`

and `1111`

. `fold()`

stops when there is nothing else in the list, returning the final `sum`

of `1111`

. Of course, Kotlin doesn’t really know it’s doing a “sum”—the choice of identifier name was ours, to make it easier to understand.

**End of sample. See AtomicKotlin.com for full early-access book.**

Previous Next

©2018 Mindview LLC. All Rights Reserved.