Fold vs Reduce in Kotlin: When to Use What? Full Breakdown

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Fold or Reduce in Kotlin: The Eternal Beginner's Question

\n\n

If you've been writing Kotlin for at least a week, you've almost certainly encountered the fold and reduce functions. At first glance, they do the same thing: iterate over a collection and accumulate a result. But the devil, as always, is in the details. The wrong choice can lead to bugs, exceptions, or just ugly code.

\n\n

In this article, we'll break down the difference between fold and reduce in Kotlin, look at live examples from real projects, and forever remember which function to use when. Let's go!

\n\n

What are fold and reduce? Basic Understanding

\n\n

Both functions are terminal operations for collections. They take all the elements and fold them into a single value. Imagine you have a stack of pancakes, and you want to make one big burger. fold and reduce are two different folding techniques.

\n\n

Reduce: The Minimalist Approach

\n\n

The reduce function uses the first element of the collection as the initial value of the accumulator. This means it simply cannot work with an empty collection — it will throw an UnsupportedOperationException.

\n\n
val numbers = listOf(1, 2, 3, 4, 5)\nval sum = numbers.reduce { acc, i -> acc + i }\nprintln(sum) // 15
\n\n

Here, acc is initially equal to 1 (the first element), then 2 is added to it, then 3, and so on. Simple and elegant, but there's a catch.

\n\n

Fold: Control Over the Start

\n\n

fold, unlike reduce, requires you to explicitly specify an initial value. This gives you full control and, more importantly, allows you to work with empty collections.

\n\n
val numbers = listOf(1, 2, 3, 4, 5)\nval sum = numbers.fold(0) { acc, i -> acc + i }\nprintln(sum) // 15\n\nval emptyList = listOf<Int>()\nval emptySum = emptyList.fold(0) { acc, i -> acc + i }\nprintln(emptySum) // 0, no error!
\n\n

See the difference? fold returns the initial value if the collection is empty. reduce will crash in that situation.

\n\n

Key Differences Between fold and reduce in Kotlin

\n\n

Let's systematize the knowledge. Here's a table to help you quickly get oriented:

\n\n
    \n
  • Initial value: In fold, you set it yourself. In reduce, it's the first element of the collection.
  • \n
  • Result type: In fold, the result type can differ from the element type (e.g., adding Ints but getting a String). In reduce, the result type always matches the element type.
  • \n
  • Empty collection: fold handles it normally (returns the initial value). reduce throws an exception.
  • \n
  • Performance: Both functions work in O(n). The performance difference is negligible.
  • \n
\n\n

Now let's see this in code.

\n\n

Example 1: Different Accumulator and Element Types

\n\n

Suppose we have a list of numbers, and we want to get a string — their sum in a readable format. fold handles this perfectly because the accumulator type (String) differs from the element type (Int).

\n\n
val numbers = listOf(1, 2, 3)\nval result = numbers.fold("Sum: ") { acc, i -> "$acc$i " }\nprintln(result) // "Sum: 1 2 3 "
\n\n

Try doing the same with reduce — the compiler will throw an error because reduce requires the accumulator type to match the element type.

\n\n

Example 2: Calculating a Sum with an Initial Value

\n\n

A common task: calculate the total sum of orders, but we already have an initial balance in the account.

\n\n
val orders = listOf(100, 250, 75)\nval initialBalance = 500\nval totalBalance = orders.fold(initialBa                

Blogs

Book Recommendations