0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Filtering with if

Guards in comprehensions.

Guards in for-comprehensions

Inside a for-comprehension you can add an if condition called a guard. It keeps only the elements that satisfy the condition, just like filter.

object Main {
  def main(args: Array[String]): Unit = {
    val evens = for (x <- 1 to 10 if x % 2 == 0) yield x
    println(evens)
  }
}

Guards desugar to withFilter

A guard if cond is rewritten into a call to withFilter (a lazy variant of filter).

  • for (x <- xs if p(x)) yield x
  • becomes xs.withFilter(p).map(x => x)
object Main {
  def main(args: Array[String]): Unit = {
    val sugar = for (x <- List(1, 2, 3, 4) if x > 2) yield x
    val desugared = List(1, 2, 3, 4).withFilter(_ > 2).map(x => x)
    println(sugar == desugared)
  }
}

All lessons in this course

  1. Desugaring for
  2. Filtering with if
  3. Multiple Generators
  4. Using with Option and Future
← Back to Scala for Backend Engineering & Functional Programming