Difference Between fold() and reduce() in Kotlin

David Mbochi Njonge Jun 30, 2022
  1. Kotlin fold() Method in Action
  2. Kotlin reduce() Method in Action
  3. Conclusion
Difference Between fold() and reduce() in Kotlin

The fold() and reduce() methods are extension functions of the Iterable interface. These methods consume a list of elements and transform them into a single element.

Since the Collection interface implements the Iterable interface, we can use the methods with any class or interface that is a sub-type of the Collection class.

In this tutorial, we will learn the difference between the fold() and reduce() methods by understanding how they work and providing an example for each case.

Kotlin fold() Method in Action

Go to IntelliJ and select File > New > Project to create a new project. Enter the project name as kotlinFoldAndReduce, or any name preferred. Select Kotlin on the Language section and Intellij on the Build System section. Press the Create button to create the project.

Once the project is created, create the folder structure com/fold for the fold() method and com/reduce for the reduce() method.

Create a new file named Main.kt under the fold folder, and copy and paste the following code into the file.

package com.fold

class Product(private val name: String,
               private val price: Int){

    fun getName(): String{
        return this.name;
    }

    fun getPrice(): Int{
        return this.price
    }
}

val  products: List<Product> = listOf(
    Product("Hp laptop",200),
    Product("Java book",320),
    Product("Iphone 13",150)
)

fun main() {
    println(products.fold(0) { total, employee ->
       total+employee.getPrice()
    });
}

The listOf() helper method we created in this code will return a list of Product elements, and from the list returned, we can invoke the fold() method.

When we invoke the fold() method, we must provide the initial value that will be used as an accumulator of the computation. Note that if the returned collection is empty, the fold() method returns the initial value we provided.

Run the code and verify that it outputs the total price of all the product elements in the list, as shown below.

Output:

670

The fold() method can also be used to check for values at least greater than or less than the initial value. The following example tests all the product elements in the list to return the product price at least greater than 300, so we set 300 as the initial value of the fold() function.

Ensure you comment out the previous example in the main method before you copy and paste this example into the file.

fun main() {
    println(products.fold(300) { expensiveProduct, product ->
        if (product.getPrice() > expensiveProduct)
            product.getPrice() else expensiveProduct
    });
}

Run the code to verify that it outputs the following value: the maximum price of all the product elements in the list.

Output:

320

Kotlin reduce() Method in Action

Create a Main.kt file under the reduce folder, and copy and paste the following code into the file.

package com.reduce

val list: List<Int> = listOf(20,40,60)

fun main() {
    println(list.reduce { sum, value ->
        sum + value
    });
}

Since the reduce() method does not have an initial value, it uses the first element of the list as the initial value. In this example, the value 20 is the first accumulator value, and the computation with 40 returns the next accumulator value.

Run the code and ensure it outputs the following result.

Output:

120

In the previous example, we have learned that the initial value provided is returned in case the list is empty. The reduce() method throws an UnsupportedOperationException, a RuntimeException, in case the list is empty.

To prevent the reduce() method from throwing RuntimeException, we can check if the list is empty before doing any computation. The following code returns a value of 0 in case the type int list is empty.

Comment on the previous example, and copy and paste this example into the file after the comment.

package com.reduce

val list: List<Int> = listOf()

fun main() {
    val data = if (list.isEmpty()) 0
    else list.reduce { sum, value ->
        sum + value
    }
    println(data);
}

Run the code and note that the value logged to the console is 0 since the list we created is empty.

Output:

0

Conclusion

In this tutorial, we have learned how to differentiate between the fold() and reduce() extension functions. We have also covered how the two methods deal with situations when the list is empty to avoid the exceptions that might be thrown.

David Mbochi Njonge avatar David Mbochi Njonge avatar

David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.

LinkedIn GitHub