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

Some and None

In this page:

  1. Some and None

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

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)
}
🔒

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.