← Back to Scala Course | Chapter 10: Pattern Matching | Lesson 7 of 7

Option with match

Matching on an Option handles both possibilities: there is a value, or there is nothing. It is like opening a gift box and reacting differently if it is empty.

In this page:

  1. Option with match
Syntax
scala
option match {
  case Some(x) => expression
  case None    => default_result
}

Option with match

Option[T] is either Some(value) or None, and matching on it, case Some(x) => ... case None => ..., is the classic structured way to handle both possibilities explicitly.

This forces you to consider the "no value" case at the pattern-matching level, rather than risking a null-pointer-style oversight. Option and its interaction with match/for-comprehensions is explored further in the next chapter on error handling.

Note: Matching on Option forces you to explicitly handle both Some and None, which is exactly the safety null references don't give you.

Example: Option with match

markup
object Main extends App {
  def describe(maybeName: Option[String]): String = maybeName match {
    case Some(name) => s"Hello, $name!"
    case None => "Hello, stranger!"
  }

  println(describe(Some("Alice")))
  println(describe(None))
}
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. Calling .get on an Option without checking, which throws NoSuchElementException for None.
  2. Forgetting the case None branch, so the compiler warns about a non-exhaustive match.
  3. Using null checks with if (x == null) when Option and match express the same idea safely.
Chapter Summary
  • match compares a value against patterns, including types, tuples, and case classes.
  • Guard conditions and nested patterns refine matches.
  • Pattern matching works with Option values.
🔒

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.