Scala Match Syntax
Scala's match expression is a fundamental part of the language, deeply integrated with case classes and sealed traits.
Basic Syntax
Key Features
1. Case Classes and Destructuring
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"
}
}
2. Guards
You can add if guards to cases.
3. Type Matching
You can match on types.
def go(device: Device) = {
device match {
case p: Phone => p.screenOff
case c: Computer => c.screenSaverOn
}
}
4. Sealed Traits and Exhaustiveness
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")
}
5. Regex Matching
Scala allows matching with Regex.