Some and None
Some means the box has something in it, and None means the box is empty. They are the two answers an Option can give.
In this page:
Syntax
val present = Some(value)
val absent = None
val maybe = Option(nullable_value)
Some and None
Some(value) wraps an actual present value, while None represents the absence of one -- both are subtypes of Option[T]. You construct them directly, or receive them as the result of an operation like a Map lookup via .get.
Pattern matching (case Some(x) => ... case None => ...) or higher-order methods like .map/.getOrElse are the idiomatic ways to work with them, rather than unsafely calling .get directly.
Warning:
Calling .get directly on an Option throws a NoSuchElementException if it's None -- prefer getOrElse, map, or pattern matching instead.
Example: Some and None
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)
}
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. #}
Common Mistakes
- Assuming
ages.get("Cara")returns the value directly, when it returnsOption[Int], so you cannot add it to anIntwithout unwrapping. - Writing
Some(null)and expectingNone, whenSome(null)holds a null value. - Comparing with
if (x == None)in a loop-heavy code whenx.isEmptyor a match is clearer.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: