模式匹配:是一种根据模式检查值的机制。
语法格式模式匹配类似于 Java 的 swith case
模式匹配中,使用 match 关键字进行声明,每个分支采用 case 关键字进行声明,当需要匹配时,就从第一个分支开始匹配,如果匹配成功,则执行对应分支的代码,如果匹配都不成功,则会执行最后的默认分支。
import scala.util.Random
val x: Int = Random.nextInt(10)
var res = x match {
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "other" // 相当于 Java 的 default
}
println(x) // 8
println(res) // other
⚠️ 若都没有匹配成功,也没有 case _ 分支,则抛出 MatchError!
匹配守卫类似于 for 的守卫,根据条件进行匹配判断。
import scala.util.Random
val x: Int = Random.nextInt(10)
var res = x match {
case i: Int if i >= 5 => "x>5 or x=5"
case j: Int if j < 5 => "x<5"
case _ => "other"
}
println(x) // 9
println(res) // x>5 or x=5
模式匹配类型
1、匹配常量:
var x:Any = 0
var res = x match {
case 0 => "Int 0"
case "0" => "String 0"
case false => "Boolean false"
case '0' => "Char 0"
case _ => "other"
}
println(res) // Int 0
2、匹配类型
def Matching(x: Any) = x match {
case i: Int => "Int"
case s: String => "String"
case l: List[_] => "List"
case a: Array[_] => "Array"
case _ => "other"
}
println(Matching(0)) // Int
println(Matching("0")) // String
println(Matching(List(1, 2, 3))) // List
println(Matching(Array(1, 2, 3))) // Array
3、匹配集合
def Matching(x: Any) = x match {
case Array(0) => "0"
case Array(0, _*) => "0 ..."
case Array(i, j) => i + "," + j
case _ => "other"
}
println(Matching(Array(0))) // 0
println(Matching(Array(0, 1, 2))) // 0 ...
println(Matching(Array(1, 2))) // 1,2
4、匹配对象及案例类
case class Stu(name: String, age: Int)
object Stu {
def apply(name: String, age: Int): Stu = new Stu(name, age)
def unapply(stu: Stu): Option[(String, Int)] = {
if (stu.name == "张三") {
Some("张三", stu.age)
} else if (stu.age == 18) {
Some(stu.name, 18)
} else {
None
}
}
}
def Matching(stu: Stu) = stu match {
case Stu("张三", age) => s"name:张三 age:不是18"
case Stu(name, 18) => s"name:不是张三 age:18"
case _ => "other"
}
println(Matching(Stu("张三", 22))) // name:张三 age:不是18
println(Matching(Stu("李四", 18))) // name:不是张三 age:18
println(Matching(null)) // other
❤️ END ❤️



