object Test{
def main(args: Array[String]): Unit = {
val sex = -1
val res = sex match {
case 1 => "man"
case 2 => "women"
// case _ => "Not Allowed!" // other
case unexcepted => unexcepted + " is Not Allowed!"
}
println(res)
}
}
//-1 is Not Allowed!
或
val sex = -1
sex match {
case 1 => println("man")
case 2 => println("women")
case _ => println(sex + " is Not Allowed!")
}
2. 类型匹配
object Test{
def main(args: Array[String]): Unit = {
for(e <- List(9, 12.3, "spark", "hadoop", 'Hello)){
val res = e match {
case _: Int => e + " is a int value."
case _: Double => e + " is a double value."
case "spark" => e
case _: String => e + " is a string value."
case _ => e + " is unknown."
}
println(res)
}
}
}
// 9 is a int value.
// 12.3