Case Classes and Pattern Matching
Pattern Matching
Choose a result by matching a value against cases.
pattern-match
A `match` expression tests a value against ordered cases and returns the first match. The `_` case is the catch-all default.
Pattern Matching
PatternMatch.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val code = 2
val label = code match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
println("code=" + code)
println("label=" + label)
}
}
object Main {
def main(args: Array[String]): Unit = {
val code = 1
val label = code match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
println("code=" + code)
println("label=" + label)
}
}
object Main {
def main(args: Array[String]): Unit = {
val code = 3
val label = code match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
println("code=" + code)
println("label=" + label)
}
}
object Main {
def main(args: Array[String]): Unit = {
val code = 9
val label = code match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
println("code=" + code)
println("label=" + label)
}
}
code ← 2, label ← two
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 2 = 2 //@code=1, 3, 94 val label→ two = code2 match {5 case 1 => "one"6 case 2 => "two"7 case 3 => "three"8 case _ => "other"9 }1011 println("code=" + code2)12 println("label=" + labeltwo)13 }14}outputcode=2 label=two
code ← 1, label ← one
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 1 = 14 val label→ one = code1 match {5 case 1 => "one"6 case 2 => "two"7 case 3 => "three"8 case _ => "other"9 }1011 println("code=" + code1)12 println("label=" + labelone)13 }14}outputcode=1 label=one
code ← 3, label ← three
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 3 = 34 val label→ three = code3 match {5 case 1 => "one"6 case 2 => "two"7 case 3 => "three"8 case _ => "other"9 }1011 println("code=" + code3)12 println("label=" + labelthree)13 }14}outputcode=3 label=three
code ← 9, label ← other
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 9 = 94 val label→ other = code9 match {5 case 1 => "one"6 case 2 => "two"7 case 3 => "three"8 case _ => "other"9 }1011 println("code=" + code9)12 println("label=" + labelother)13 }14}outputcode=9 label=other
Follow the Match
codestarts at2.- The
matchchecks cases from top to bottom. case 1does not match2.case 2matches and returnstwo.- The program prints
code=2andlabel=two. | code | matching case | label | | ---: | --- | --- | | 1 | case 1 | one | | 2 | case 2 | two | | 3 | case 3 | three | | 9 | case _ | other |
Exercise: PatternMatch.scala
Reproduce code=2 and label=two, then use codes 1, 3, and 9 to predict labels one, three, and other.