0Pricing
Scala for Backend Engineering & Functional Programming · Leçon

Filtrer avec if

Gardes dans les compréhensions

Filtrer avec if est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Scala for Backend Engineering & Functional Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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)
  }
}

Why withFilter, not filter

withFilter is lazy: it does not build an intermediate collection. The condition is applied only when the following map or flatMap runs, which saves memory and work.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4, 5, 6)
    val result = for (n <- nums if n % 3 == 0) yield n * 100
    println(result)
  }
}

Multiple guards

You can chain several guards. They combine like a logical AND: an element must satisfy all conditions to survive.

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

Guards with multiple generators

Guards can appear after any generator and filter that level of iteration. Place the guard right after the generator whose values it tests.

object Main {
  def main(args: Array[String]): Unit = {
    val coprimeSums = for {
      x <- 1 to 3
      y <- 1 to 3
      if x != y
    } yield (x, y)
    println(coprimeSums)
  }
}

Combining a guard and a value binding

You can freely mix guards (if) with value bindings (=). Order matters: a binding defined before a guard can be used inside that guard.

object Main {
  def main(args: Array[String]): Unit = {
    val result = for {
      x <- 1 to 6
      square = x * x
      if square > 10
    } yield square
    println(result)
  }
}

Guards on String collections

Guards work with any predicate, not just numeric ones. Here we filter words by length.

object Main {
  def main(args: Array[String]): Unit = {
    val words = List("scala", "go", "java", "rust", "c")
    val longWords = for (w <- words if w.length >= 4) yield w.toUpperCase
    println(longWords)
  }
}

Filtering Options

For an Option, a guard that fails turns the result into None. This makes for-comprehensions a clean way to validate optional values.

object Main {
  def main(args: Array[String]): Unit = {
    val ok  = for (x <- Some(8) if x > 5) yield x
    val bad = for (x <- Some(3) if x > 5) yield x
    println(ok)
    println(bad)
  }
}

Guard position changes meaning

A guard only sees values bound above it. Putting it before a generator that it needs will not compile. Always place a guard after the relevant generator.

object Main {
  def main(args: Array[String]): Unit = {
    val result = for {
      x <- 1 to 3
      y <- 1 to 3
      if x + y == 4
    } yield s"$x + $y = ${x + y}"
    result.foreach(println)
  }
}

Guards versus a final filter

You could filter the result after the comprehension, but a guard filters during iteration. With multiple generators, guards can prune branches early, doing less total work.

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

Readable validation pipelines

Stacking guards reads like a checklist of conditions. This is one of the most idiomatic uses of for-comprehensions in real Scala code.

object Main {
  def main(args: Array[String]): Unit = {
    val valid = for {
      n <- List(4, 7, 12, 15, 20)
      if n > 5
      if n < 18
      if n % 2 == 0
    } yield n
    println(valid)
  }
}

Quick Check

What method does a guard (if) in a for-comprehension desugar into?

Recap

You learned about guards in for-comprehensions:

  • if cond filters elements during iteration
  • Guards desugar to withFilter (lazy filtering)
  • Multiple guards combine like logical AND
  • A guard only sees values bound above it
  • Guards mix freely with generators and = bindings

Questions Fréquemment Posées

La leçon « Filtrer avec if » est-elle gratuite ?

Oui — le texte complet de « Filtrer avec if » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Scala for Backend Engineering & Functional Programming, passe à CoddyKit PRO. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Filtrer avec if » ?

Gardes dans les compréhensions Tu pratiques Scala for Backend Engineering & Functional Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Scala for Backend Engineering & Functional Programming ?

Aucune expérience préalable n'est requise. Scala for Backend Engineering & Functional Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.

Combien de temps prend la leçon « Filtrer avec if » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Scala for Backend Engineering & Functional Programming ?

Oui. Chaque leçon Scala for Backend Engineering & Functional Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Désucrage de for
  2. Filtrer avec if
  3. Générateurs multiples
  4. Utiliser Option et Future
← Retour à Scala for Backend Engineering & Functional Programming