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

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:

  1. Some and None
Syntax
scala
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

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. #}
Common Mistakes
  1. Assuming ages.get("Cara") returns the value directly, when it returns Option[Int], so you cannot add it to an Int without unwrapping.
  2. Writing Some(null) and expecting None, when Some(null) holds a null value.
  3. Comparing with if (x == None) in a loop-heavy code when x.isEmpty or a match is clearer.
🔒

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.