Option के साथ for Comprehension
एक for comprehension कई Option boxes को chain कर सकता है और रुक जाता है अगर इनमें से कोई खाली हो। यह एक treasure hunt जैसा है जहां आप तभी आगे बढ़ते हैं जब हर clue मिल जाए।
In this page:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह उम्मीद करना कि
Optionvalues पर एकforएक साधारण number देगा, जबकि यहOption[Int]देता है। - एक ही
forमेंOptionऔरListgenerators मिलाना, जो एक type error देता है। - यह मान लेना कि
Noneके बाद code जारी रहता है, जबकि पूरा comprehension जैसे ही एक generatorNoneहो,Noneदे देता है।
चैप्टर सारांश
SomeऔरNoneके साथOptionउन values को represent करता है जो गायब हो सकती हैं।mapऔरgetOrElseOptionvalues के साथ काम करते हैं।SuccessऔरFailureके साथTry,Either, और for comprehensions errors को handle करते हैं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: