Scala — Pattern matching with match and case
A Scala match expression selects the first matching case. A pattern alternative lets several literal values share one outcome.
A simple example
Match one case
- Start with Value 2
- Do this Match case 2
- Result two
object Lesson extends App {
val word = 2 match {
case 2 => "two"
case _ => "other"
}
println(word)
}
two
Route several event states to one action
Map queued and retry to the same pending action. A sent event is complete, and an unrecognized state is sent for review. The wildcard case makes the mapping total for strings such as unknown. Put broader patterns after specific alternatives.
A parcel dashboard receives status updates. A queued parcel and a parcel awaiting retry both belong in the pending tray. Mark a sent parcel done and send unfamiliar statuses for review.
Run the example
Use Scala 2.13. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
def route(state: String): String = state match {
case "queued" | "retry" => "pending"
case "sent" => "done"
case _ => "review"
}
def main(args: Array[String]): Unit = {
List("queued", "retry", "sent", "unknown").foreach(state => println(route(state)))
}
}
pending pending done review
Both pending states share one result. The other branches distinguish a known completion from a new or misspelled status.
Try it yourself
What should an unrecognized state such as paused produce?
Check your answer
It produces review. Add an explicit case when the application defines how to handle that state.