Difference between "fold" and "reduce" in Kotlin


Kotlin is a cross-platform and statically typed general-purpose programming language. Kotlin provides many optional methods to traverse through the collections. fold() and reduce() are two different methods, both are helpful for traversing a collection. In this article, we will see how and when to use these two methods.

Example – fold()

If we want to traverse through a collection serially, then we can use fold().

  • fold() takes one initial value and one operation to perform the operation on the initial value.

  • There are different kinds of fold(), for example, foldRight() folds from right to left. By default, fold() will traverse from left to right.

The following example demonstrates how to use fold() to traverse through a collection.

fun main(args: Array<String>) {

   val MyTotal = listOf(1, 2, 3, 4, 5).fold(0) {
      initialValue, result -> result + initialValue
   }
   print("The sum of list members: " +MyTotal)
}

Output

fold() will start the operation from the 0th index and it will end its operation and store the final value in MyTotal.

The sum of list members: 15

Example - reduce()

reduce() is one of the default methods in Kotlin that helps to convert a given set of collection into a single set output result. reduce() is one of the built-in functions that can be applied on a given collection. It takes the first and second elements as the operation argument and this is the main difference between reduce() and fold().

fun main(args: Array<String>) {
   val x = listOf(1,2,3,4,5,6,7,8,9)
   val y = x.reduce { y, vars -> y + vars }
   println("The value of reduce() ---> "+y)
}

Output

It will yield the following output

The value of reduce() ---> 45

Here, reduce() starts its operation from the first two elements, applies the function on them, and stores the result in "y". It continues the operation till the last element is reached and returns the final value.

Updated on: 23-Nov-2021

905 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements