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:
Syntax
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
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))
}
Login to try C/C++/Java/PHP code in the editor
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
- Calling
.geton anOptionwithout checking, which throwsNoSuchElementExceptionforNone. - Forgetting the
case Nonebranch, so the compiler warns about a non-exhaustive match. - Using
nullchecks withif (x == null)whenOptionandmatchexpress the same idea safely.
Chapter Summary
matchcompares a value against patterns, including types, tuples, and case classes.- Guard conditions and nested patterns refine matches.
- Pattern matching works with
Optionvalues.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: