← Back to Scala Course | Chapter 10: Pattern Matching | Lesson 5 of 7

Guard Conditions क्या हैं

एक guard किसी match case में एक अतिरिक्त condition जोड़ता है, जैसे एक bouncer जो आपका ticket और साथ में आपकी उम्र भी जांचता है। case सिर्फ तभी गिना जाता है जब rule भी true हो।

In this page:

  1. Guard Conditions
Syntax
scala
value match {
  case x if condition => expression
  case _              => default_result
}

Guard Conditions

एक guard, जिसे case pattern if condition => लिखा जाता है, किसी pattern में एक अतिरिक्त boolean check जोड़ता है जो उस branch के match करने के लिए भी true होना चाहिए।

अगर guard की condition false है, तो matching अगले case पर ऐसे जारी रहती है जैसे pattern ने बिल्कुल match ही न किया हो। Guards आपको वे conditions express करने देते हैं जिन्हें सिर्फ structural patterns capture नहीं कर सकते।

Note: किसी guard की condition उसी pattern में पहले bound किए गए variables को reference कर सकती है, जैसे case Point(x, y) if x == y => ...।

उदाहरण: Guard Conditions

markup
object Main extends App {
  def classify(n: Int): String = n match {
    case x if x < 0 => "negative"
    case 0 => "zero"
    case x if x % 2 == 0 => "positive even"
    case _ => "positive odd"
  }

  println(classify(-5))
  println(classify(0))
  println(classify(4))
  println(classify(7))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. guard का if arrow के बाद रखना, जैसे case x => if x < 0, जबकि यह => से पहले आता है।
  2. किसी general case के बाद guarded case रखना, जिससे guard कभी जांचा ही नहीं जाता।
  3. यह मान लेना कि guard सभी cases के लिए चलता है, जबकि यह सिर्फ उस case पर लागू होता है जिससे यह जुड़ा है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.