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

Option with match

In this page:

  1. Option with match

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

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.