Kotlin – Difference between fold and reduce in Kotlin, When to use which

foldkotlinreduce

I am pretty confused with both functions fold() and reduce() in Kotlin, can anyone give me a concrete example that distinguishes both of them?

Best Answer

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.

For example, take the following code that calculates the sum of a list of integers:

listOf(1, 2, 3).fold(0) { sum, element -> sum + element }

The first call to the lambda will be with parameters 0 and 1.

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. For example, if you were looking for the maximum value inside a list, but for some reason want to return at least 10, you could do the following:

listOf(1, 6, 4).fold(10) { max, element ->
    if (element > max) element else max
}

reduce doesn't take an initial value, but instead starts with the first element of the collection as the accumulator (called sum in the following example).

For example, let's do a sum of integers again:

listOf(1, 2, 3).reduce { sum, element -> sum + element }

The first call to the lambda here will be with parameters 1 and 2.

You can use reduce when your operation does not depend on any values other than those in the collection you're applying it to.