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

match के साथ Option

किसी Option पर matching दोनों संभावनाओं को handle करता है: एक value है, या कुछ नहीं है। यह किसी gift box को खोलकर अलग react करने जैसा है अगर वह खाली हो।

In this page:

  1. Option with match
Syntax
scala
option match {
  case Some(x) => expression
  case None    => default_result
}

Option with match

Option[T] या तो Some(value) है या None, और इस पर match करना, case Some(x) => ... case None => ..., दोनों संभावनाओं को explicitly handle करने का classic संरचित तरीका है।

यह आपको null-pointer-style चूक का जोखिम उठाने के बजाय pattern-matching स्तर पर "कोई value नहीं" वाले case पर विचार करने के लिए मजबूर करता है। Option और match/for-comprehensions के साथ इसकी interaction को error handling वाले अगले chapter में और explore किया गया है।

Note: किसी Option पर matching आपको Some और None दोनों को explicitly handle करने के लिए मजबूर करती है, जो बिल्कुल वह सुरक्षा है जो null references नहीं देते।

उदाहरण: Option with match

markup
object Main extends App {
  def describe(maybeName: Option[String]): String = maybeName match {
    case Some(name) => s"Hello, $name!"
    case None => "Hello, stranger!"
  }

  println(describe(Some("Alice")))
  println(describe(None))
}
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. बिना जांचे किसी Option पर .get call करना, जो None के लिए NoSuchElementException फेंकता है।
  2. case None branch भूल जाना, जिससे compiler एक non-exhaustive match की चेतावनी देता है।
  3. if (x == null) से null checks का उपयोग करना जब Option और match एक ही idea को सुरक्षित रूप से express करते हैं।
चैप्टर सारांश
  • match किसी value को types, tuples, और case classes सहित patterns से compare करता है।
  • Guard conditions और nested patterns matches को परिष्कृत करते हैं।
  • Pattern matching Option values के साथ काम करता है।
🔒

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.