0 votes
in Kotlin by
What is basic difference between fold and reduce in Kotlin? When to use which?

1 Answer

0 votes
by

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 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.

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)

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

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

Related questions

0 votes
asked Oct 5, 2021 in Kotlin by rajeshsharma
0 votes
asked Oct 5, 2021 in Kotlin by rajeshsharma
...