beps/docs/proposals/BEP-002-match/context/scala.md
Scala's match expression is a fundamental part of the language, deeply integrated with case classes and sealed traits.
val x = 1
val result = x match {
case 1 => "one"
case 2 => "two"
case _ => "other"
}
Scala's case classes are designed for pattern matching.
sealed trait Notification
case class Email(sender: String, title: String, body: String) extends Notification
case class SMS(caller: String, message: String) extends Notification
case class VoiceRecording(contactName: String, link: String) extends Notification
def showNotification(notification: Notification): String = {
notification match {
case Email(sender, title, _) =>
s"You got an email from $sender with title: $title"
case SMS(number, message) =>
s"You got an SMS from $number! Message: $message"
case VoiceRecording(name, link) =>
s"You received a Voice Recording from $name! Click the link to hear it: $link"
}
}
You can add if guards to cases.
case Email(sender, _, _) if sender == "[email protected]" => "Important!"
You can match on types.
def go(device: Device) = {
device match {
case p: Phone => p.screenOff
case c: Computer => c.screenSaverOn
}
}
If you match on a sealed trait, the compiler checks for exhaustiveness.
sealed trait Answer
case object Yes extends Answer
case object No extends Answer
// Warning: match may not be exhaustive. It would fail on the following input: No
val x: Answer = Yes
x match {
case Yes => println("Yes")
}
Scala allows matching with Regex.
val date = "2023-01-01"
val dateRegex = """(\d{4})-(\d{2})-(\d{2})""".r
date match {
case dateRegex(year, month, day) => s"$year was a good year"
case _ => "Not a date"
}