Case Classes and Pattern Matching
Default Cases
Handle unlisted values with a catch-all case.
default-case
The `_` case matches anything the earlier cases missed. Its body can still read the original value to build a fallback result.
Default Cases
DefaultCase.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val code = 9
val label = code match {
case 1 => "one"
case 2 => "two"
case _ => "code:" + code
}
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 _ => "code:" + code
}
println("code=" + code)
println("label=" + label)
}
}
object Main {
def main(args: Array[String]): Unit = {
val code = 2
val label = code match {
case 1 => "one"
case 2 => "two"
case _ => "code:" + code
}
println("code=" + code)
println("label=" + label)
}
}
code ← 9, label ← code:9
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 9 = 9 //@code=1, 24 val label→ code:9 = code9 match {5 case 1 => "one"6 case 2 => "two"7 case _ => "code:" + code98 }910 println("code=" + code9)11 println("label=" + labelcode:9)12 }13}outputcode=9 label=code:9
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 _ => "code:" + code18 }910 println("code=" + code1)11 println("label=" + labelone)12 }13}outputcode=1 label=one
code ← 2, label ← two
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 2 = 24 val label→ two = code2 match {5 case 1 => "one"6 case 2 => "two"7 case _ => "code:" + code28 }910 println("code=" + code2)11 println("label=" + labeltwo)12 }13}outputcode=2 label=two