Gardes et liaison
Conditions dans les correspondances
Gardes et liaison est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 3 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.
What Is a Guard?
A guard adds a boolean condition to a case using if. The case matches only when the pattern fits and the guard is true.
Guards let a single pattern split into finer cases based on the value.
Adding an if Guard
Write the guard after the pattern: case n if n > 0 =>. If the condition is false, matching continues to the next case.
object Main {
def sign(n: Int): String = n match {
case x if x > 0 => "positive"
case x if x < 0 => "negative"
case _ => "zero"
}
def main(args: Array[String]): Unit = {
println(sign(5))
println(sign(-3))
println(sign(0))
}
}Binding Then Guarding
The guard can reference the name you bound in the pattern. This is how you test properties of the matched value.
object Main {
def fizz(n: Int): String = n match {
case x if x % 15 == 0 => "FizzBuzz"
case x if x % 3 == 0 => "Fizz"
case x if x % 5 == 0 => "Buzz"
case x => x.toString
}
def main(args: Array[String]): Unit = {
println(fizz(15))
println(fizz(9))
println(fizz(7))
}
}Guards on Ranges
Guards are perfect for ranges, which literal patterns cannot express directly.
object Main {
def band(score: Int): String = score match {
case s if s >= 90 => "A"
case s if s >= 80 => "B"
case s if s >= 70 => "C"
case _ => "F"
}
def main(args: Array[String]): Unit = {
println(band(95))
println(band(83))
println(band(60))
}
}Pattern Binding With @
The @ symbol binds the whole matched value to a name while still pattern matching its structure.
Here whole @ pattern means: match pattern, and also call the matched value whole.
object Main {
def main(args: Array[String]): Unit = {
val x: Any = 7
val msg = x match {
case n @ (_: Int) => s"int value is $n"
case _ => "other"
}
println(msg)
}
}Binding in Collections
The @ binding is especially handy with structured patterns, like capturing a whole list while also inspecting its head.
object Main {
def describe(xs: List[Int]): String = xs match {
case all @ (first :: _) => s"starts with $first, full = $all"
case Nil => "empty"
}
def main(args: Array[String]): Unit = {
println(describe(List(1, 2, 3)))
println(describe(Nil))
}
}Combining Type Pattern and Guard
You can mix a type pattern with a guard. First the type is checked, then the boolean condition.
object Main {
def label(x: Any): String = x match {
case s: String if s.length > 3 => "long string"
case s: String => "short string"
case _ => "not a string"
}
def main(args: Array[String]): Unit = {
println(label("hello"))
println(label("hi"))
println(label(42))
}
}Multiple Conditions
A guard is just a boolean expression, so you can combine conditions with && and ||.
object Main {
def category(age: Int): String = age match {
case a if a >= 13 && a <= 19 => "teen"
case a if a < 13 => "child"
case _ => "adult"
}
def main(args: Array[String]): Unit = {
println(category(15))
println(category(8))
println(category(40))
}
}Guards Do Not Fall Through
If a pattern matches but its guard is false, Scala moves on to the next case, not the next guard of the same pattern.
Make sure a later case can catch values that fail every guard.
object Main {
def test(n: Int): String = n match {
case x if x > 100 => "big"
case x => s"not big: $x"
}
def main(args: Array[String]): Unit = {
println(test(200))
println(test(5))
}
}Why Guards and Binding?
Together, guards and @ bindings make pattern matching expressive:
- Guards add conditions like ranges and divisibility
@captures the whole value while destructuring it- They keep branching logic compact and readable
Putting It Together
This example binds the value, checks a guard, and provides a fallback.
object Main {
def temp(c: Int): String = c match {
case t if t >= 30 => s"hot ($t)"
case t if t >= 15 => s"mild ($t)"
case t => s"cold ($t)"
}
def main(args: Array[String]): Unit = {
println(temp(35))
println(temp(20))
println(temp(5))
}
}Quick Check
Test your understanding of guards and binding.
Recap
You learned to refine matches:
- A guard is an
ifcondition after a pattern - If the guard is false, matching moves to the next case
- The
@operator binds the whole value while destructuring - Guards combine with type patterns and boolean operators
Questions Fréquemment Posées
La leçon « Gardes et liaison » est-elle gratuite ?
Oui — le texte complet de « Gardes et liaison » 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 « Gardes et liaison » ?
Conditions dans les correspondances 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 3 sur 4.
Combien de temps prend la leçon « Gardes et liaison » ?
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.