0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Folding and Reducing

foldLeft and reduce.

Combining elements into one

Sometimes you need to combine all elements of a collection into a single value, like a sum or a concatenation. Scala provides fold, foldLeft, foldRight, and reduce for this.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4)
    println(nums.sum)
    println(nums.product)
  }
}

reduce: combine without a seed

reduce combines elements pairwise using a binary function. It needs at least one element, otherwise it throws an exception.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4)
    val total = nums.reduce((a, b) => a + b)
    println(total)
    val max = nums.reduce((a, b) => if (a > b) a else b)
    println(max)
  }
}

All lessons in this course

  1. List, Vector, Set, Map
  2. Transformations
  3. Folding and Reducing
  4. Grouping and Sorting
← Back to Scala for Backend Engineering & Functional Programming