Some and None
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: