Scala 中的 case 语句支持任何类型;而 Java 中 case 语句仅支持整型、枚举和字符串常量;
Scala 中每个分支语句后面不需要写 break,因为在 case 语句中 break 是隐含的,默认就有;
在 Scala 中 match 语句是有返回值的,而 Java 中 switch 语句是没有返回值的。如下:
object ScalaApp extends App {
def matchTest(x: Int) = x match {
case 1 => "one"
case 2 => "two"
case _ if x > 9 && x < 100 => "两位数" //支持条件表达式 这被称为模式守卫
case _ => "other"
}
println(matchTest(1)) //输出 one
println(matchTest(10)) //输出 两位数
println(matchTest(200)) //输出 other
}
1.2 用作类型检查
object ScalaApp extends App {
def matchTest[T](x: T) = x match {
case x: Int => "数值型"
case x: String => "字符型"
case x: Float => "浮点型"
case _ => "other"
}
println(matchTest(1)) //输出 数值型
println(matchTest(10.3f)) //输出 浮点型
println(matchTest("str")) //输出 字符型
println(matchTest(2.1)) //输出 other
}
1.3 匹配数据结构
匹配元组示例:
object ScalaApp extends App {
def matchTest(x: Any) = x match {
case (0, _, _) => "匹配第一个元素为 0 的元组"
case (a, b, c) => println(a + "~" + b + "~" + c)
case _ => "other"
}
println(matchTest((0, 1, 2))) // 输出: 匹配第一个元素为 0 的元组
matchTest((1, 2, 3)) // 输出: 1~2~3
println(matchTest(Array(10, 11, 12, 14))) // 输出: other
}
匹配数组示例:
object ScalaApp extends App {
def matchTest[T](x: Array[T]) = x match {
case Array(0) => "匹配只有一个元素 0 的数组"
case Array(a, b) => println(a + "~" + b)
case Array(10, _*) => "第一个元素为 10 的数组"
case _ => "other"
}
println(matchTest(Array(0))) // 输出: 匹配只有一个元素 0 的数组
matchTest(Array(1, 2)) // 输出: 1~2
println(matchTest(Array(10, 11, 12))) // 输出: 第一个元素为 10 的数组
println(matchTest(Array(3, 2, 1))) // 输出: other
}