Case Classes and Pattern Matching
Default Cases
Handle unlisted values with a catch-all case.
Default Cases
DefaultCase.scala
object Main {
def main(args: Array[String]): Unit = {
val code =
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 =
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 =
val label = code match {
case 1 => "one"
case 2 => "two"
case _ => "code:" + code
}
println("code=" + code)
println("label=" + label)
}
}
default-case
The `_` case matches anything the earlier cases missed. Its body can still read the original value to build a fallback result.