Option with match
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: