0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

foldLeft and foldRight

Collapse collections to a value.

foldLeft and foldRight is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Folding a Collection

Folding collapses a collection into a single value by repeatedly combining elements with an accumulator.

The accumulator pattern you learned is exactly what fold abstracts. Instead of writing the recursive helper yourself, you pass in a starting value and a combining function.

foldLeft Basics

foldLeft takes an initial accumulator and a function (acc, element) and walks the collection from left to right.

At each step it replaces the accumulator with the function's result.

val xs = List(1, 2, 3, 4)
val total = xs.foldLeft(0)((acc, x) => acc + x)

@main def run(): Unit =
  println(total)  // 10

How foldLeft Associates

foldLeft brackets from the left. For List(1, 2, 3) with seed z it computes f(f(f(z, 1), 2), 3).

The accumulator is the left argument, so it accumulates as you move rightward through the list.

// List(1, 2, 3).foldLeft(0)(_ + _)
// = ((0 + 1) + 2) + 3
// = 6

foldRight Basics

foldRight also combines elements but starts from the right.

Its function takes (element, acc), with the element on the left and the accumulator on the right.

val xs = List(1, 2, 3, 4)
val total = xs.foldRight(0)((x, acc) => x + acc)

@main def run(): Unit =
  println(total)  // 10

How foldRight Associates

foldRight brackets from the right. For List(1, 2, 3) with seed z it computes f(1, f(2, f(3, z))).

The seed sits at the far right and the list is combined inward from the end.

// List(1, 2, 3).foldRight(0)(_ + _)
// = 1 + (2 + (3 + 0))
// = 6

When Direction Matters

For associative, commutative operations like sum or product, both folds give the same answer.

For non-commutative operations like subtraction or list building, the direction changes the result. Choose deliberately.

val xs = List(1, 2, 3)
val l = xs.foldLeft(0)(_ - _)   // ((0-1)-2)-3 = -6
val r = xs.foldRight(0)(_ - _)  // 1-(2-(3-0)) = 2

@main def run(): Unit =
  println((l, r))  // (-6, 2)

Building a List

foldRight is the natural choice for rebuilding a list in order, because it works from the tail inward and prepending keeps elements in place.

This maps each element while preserving order.

val xs = List(1, 2, 3)
val doubled = xs.foldRight(List.empty[Int]) { (x, acc) =>
  (x * 2) :: acc
}

@main def run(): Unit =
  println(doubled)  // List(2, 4, 6)

foldLeft Reverses

If you build a list with foldLeft and prepend, the result comes out reversed, because elements are added front-first as you move rightward.

This is sometimes exactly what you want.

val xs = List(1, 2, 3)
val rev = xs.foldLeft(List.empty[Int]) { (acc, x) =>
  x :: acc
}

@main def run(): Unit =
  println(rev)  // List(3, 2, 1)

Stack Safety

foldLeft is tail recursive and runs as a loop, so it is safe on huge collections.

foldRight on a List is not tail recursive and can overflow the stack for very long lists. Prefer foldLeft when you do not need right-to-left order.

// Safe even for millions of elements:
val n = (1 to 1000000).foldLeft(0L)(_ + _)

// foldRight on a long List risks StackOverflowError

Changing the Result Type

The accumulator type can differ from the element type.

Here we fold a list of ints into a string, so the seed is an empty string and each step appends.

The fold's type is driven by the seed.

val xs = List(1, 2, 3)
val s = xs.foldLeft("")((acc, x) => acc + x.toString)

@main def run(): Unit =
  println(s)  // "123"

Fold as a Swiss Army Knife

Many list operations are special cases of fold: sum, product, length, max, map, filter, reverse.

Recognizing the fold underneath them helps you write concise, declarative code instead of hand-rolled recursion.

val xs = List(4, 1, 7, 3)
val maxV = xs.foldLeft(Int.MinValue)(_ max _)
val len  = xs.foldLeft(0)((acc, _) => acc + 1)

@main def run(): Unit =
  println((maxV, len))  // (7, 4)

Quick Check

Reason about fold direction and the seed position.

Recap

foldLeft walks left to right with the accumulator on the left and computes ((z op a) op b) op c. It is tail recursive and stack safe.

foldRight walks right to left with the seed on the right and computes a op (b op (c op z)). It suits order-preserving list construction but can overflow on long lists.

The seed determines the result type, so folds can transform a collection into any value.

Frequently asked questions

Is the “foldLeft and foldRight” lesson free?

Yes — the full text of “foldLeft and foldRight” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.

What will I learn in “foldLeft and foldRight”?

Collapse collections to a value. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “foldLeft and foldRight” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Thinking Recursively
  2. Accumulator Patterns
  3. foldLeft and foldRight
  4. reduce and aggregate
← Back to Scala for Backend Engineering & Functional Programming