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

Some और None

Some का मतलब है कि box में कुछ है, और None का मतलब है कि box खाली है। ये दोनों जवाब हैं जो एक Option दे सकता है।

In this page:

  1. Some and None
Syntax
scala
val present = Some(value)
val absent = None
val maybe = Option(nullable_value)

Some and None

Some(value) एक वास्तविक मौजूद value को wrap करता है, जबकि None उसकी अनुपस्थिति को represent करता है -- दोनों Option[T] के subtypes हैं। आप इन्हें सीधे बनाते हैं, या किसी operation के result के रूप में पाते हैं, जैसे .get के ज़रिए किसी Map lookup का।

Pattern matching (case Some(x) => ... case None => ...) या .map/.getOrElse जैसे higher-order methods इनके साथ काम करने के idiomatic तरीके हैं, सीधे असुरक्षित रूप से .get call करने के बजाय।

Warning: किसी Option पर सीधे .get call करना NoSuchElementException फेंकता है अगर यह None हो -- इसके बजाय getOrElse, map, या pattern matching को प्राथमिकता दें।

उदाहरण: Some and None

markup
object Main extends App {
  val ages = Map("Alice" -> 30, "Bob" -> 25)

  val aliceAge: Option[Int] = ages.get("Alice")
  val caraAge: Option[Int] = ages.get("Cara")

  println(aliceAge)
  println(caraAge)
}
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. यह मान लेना कि ages.get("Cara") सीधे value return करता है, जबकि यह Option[Int] return करता है, इसलिए आप इसे unwrap किए बिना किसी Int में नहीं जोड़ सकते।
  2. Some(null) लिखना और None की उम्मीद करना, जबकि Some(null) एक null value रखता है।
  3. loop-heavy code में if (x == None) से compare करना जब x.isEmpty या एक match ज़्यादा साफ़ हो।
🔒

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.