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

The Option Type

In this page:

  1. The Option Type

The Option Type

Option[T] represents a value that might or might not be present, replacing the need for null to signal absence. It's a container holding either exactly one value or none at all, forcing callers to explicitly handle the "missing" case rather than risking a null-pointer error. Methods that might not find a result, like a map lookup, conventionally return an Option instead of null.

Note: Prefer Option over null for any value that might legitimately be absent -- it makes the possibility of absence visible in the type itself.

Example: The Option Type

markup
object Main extends App {
  val found: Option[Int] = Some(42)
  val missing: Option[Int] = None

  println(found)
  println(missing)
  println(found.isDefined)
  println(missing.isEmpty)
}
🔒

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.