第七章 模式匹配
Scala中的模式匹配类似与Java中的switch语法,但是scala从语法中补充了更多的功能,所以更加强大。
7.1 基本语法
模式匹配语法中,采用match关键字声明,每个分支采用case关键字进行声明,当需要匹配时,会从第一个case分支开始,如果匹配成功,那么执行对应的逻辑代码,如果匹配不成功,继续执行下一个分支进行判断。如果所有case都不匹配,那么会执行case _分支,类似于Java中default语句。
val student1 = Student1("alice", 18)
val student2 = Student1("alice", 19)
val student3 = Student1("bob", 18)
val result = student1 match {
case Student1("alice", 18) => "Yes, this is alice 18"
case _ => "No"
}
println(result)
说明
(1)如果所有case都不匹配,那么会执行case _ 分支,类似于Java中default语句,若此时没有case _ 分支,那么会抛出MatchError。
(2)每个case中,不需要使用break语句,自动中断case。
(3)match case语句可以匹配任何类型,而不只是字面量。
(4)=> 后面的代码块,直到下一个case语句之前的代码是作为一个整体执行,可以使用{}括起来,也可以不括。
7.2 模式守卫
1)说明
如果想要表达匹配某个范围的数据,就需要在模式匹配中增加条件守卫。
2)案例实操
def abs(num: Int): Int = {
num match {
case i if i > 0 => i
case i if i < 0 => -i
case _ => 0
}
}
println(abs(8))
println(abs(-235))
println(abs(0))
7.3 模式匹配类型
7.3.1 匹配常量
1)说明
Scala中,模式匹配可以匹配所有的字面量,包括字符串,字符,数字,布尔值等等。
2)案例实操、
def describeConst(x: Any): Any = x match {
case 10 => "Int Ten"
case "hello" => "String hello"
case true => "Boolean true"
case '+' => "Char +"
case _ =>
}
println(describeConst(10))
println(describeConst("hello"))
println(describeConst(true))
println(describeConst("abc"))
7.3.2 匹配类型
1)说明
需要进行类型判断时,可以使用前文所学的isInstanceOf[T]和asInstanceOf[T],也可使用模式匹配实现同样的功能。
2)案例实操
def describeType(x: Any): String = x match {
case i: Int => "Int " + i
case s: String => "String " + s
case b: Boolean => "Boolean " + b
case l: List[String] => "List " + l // 泛型擦除
case arr: Array[Int] => "Array[Int] " + arr.mkString(",")
case _ => "something else"
}
println(describeType(10))
println(describeType("hello"))
println(describeType(true))
println(describeType("abc"))