← Back to Scala Course | Chapter 11: Error Handling & Option | Lesson 7 of 7

Option के साथ for Comprehension

एक for comprehension कई Option boxes को chain कर सकता है और रुक जाता है अगर इनमें से कोई खाली हो। यह एक treasure hunt जैसा है जहां आप तभी आगे बढ़ते हैं जब हर clue मिल जाए।
Syntax
scala
val result = for {
  a <- option1
  b <- option2
} yield expression

for Comprehension with Option

एक for comprehension सीधे Option values के साथ काम करता है, जैसे ही कोई generator None produce करे short-circuit होकर None बन जाता है, और सिर्फ तभी Some(result) देता है जब हर step सफल हो।

यह chained .flatMap calls में desugar होता है, वही mechanism जो पहले List के लिए कवर किया गया था, बस Option पर लागू होता है। यह nested .flatMap/.map calls या pattern matches के pyramid के बिना कई optional values को combine करने का एक साफ़ तरीका है।

Note: कई Options पर एक for comprehension short-circuit होकर None बन जाता है जैसे ही इनमें से कोई एक None हो -- किसी explicit check की ज़रूरत नहीं।

उदाहरण: for Comprehension with Option

markup
object Main extends App {
  val a: Option[Int] = Some(5)
  val b: Option[Int] = Some(10)
  val c: Option[Int] = None

  val sumAB = for {
    x <- a
    y <- b
  } yield x + y

  val sumWithMissing = for {
    x <- a
    y <- c
  } yield x + y

  println(sumAB)
  println(sumWithMissing)
}
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 values पर एक for एक साधारण number देगा, जबकि यह Option[Int] देता है।
  2. एक ही for में Option और List generators मिलाना, जो एक type error देता है।
  3. यह मान लेना कि None के बाद code जारी रहता है, जबकि पूरा comprehension जैसे ही एक generator None हो, None दे देता है।
चैप्टर सारांश
  • Some और None के साथ Option उन values को represent करता है जो गायब हो सकती हैं।
  • map और getOrElse Option values के साथ काम करते हैं।
  • Success और Failure के साथ Try, Either, और for comprehensions errors को handle करते हैं।
🔒

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.