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

The Option Type

An Option is a box that may hold a value or may be empty, and it warns you to check before using it. It helps avoid the crashes that come from using nothing.

In this page:

  1. The Option Type
Syntax
scala
val option: Option[Type] = Some(value)
val empty: Option[Type] = None
option.isDefined

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)
}
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. Returning null instead of None, which brings back the NullPointerException that Option avoids.
  2. Wrapping a possibly-null value with Some(x), when Option(x) returns None if x is null.
  3. Calling .get on None, which throws; use getOrElse, map or pattern matching.
🔒

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.