(一)变量声明中的模式匹配
object matchcase06 {
def main(args: Array[String]): Unit = {
val arr = Array(1,2,3,4,5)
// 定义三个变量,分别是将数组arr的前三个元素的值?
var a = arr(0)
var b = arr(1)
var c = arr(2)
println("a=" + a + " b=" + b + " c=" + c)
// 将数组arr(x,y,z)的前三个元素的值赋值给a,b,c
val Array(x, y, z, _*) = arr
// _* 占位符,表示后面的部分放在哪儿
println("x=" + x + " y=" + y + " z=" + z)
}
}
其中: _*表示多个其他的元素值。
(二)守卫语句的格式
守卫语句紧跟在case模式之后,通过if关键字引入,格式如下:
value match {
case pattern if guardCondition => result
// 其他case语句...
}
其中,value是要进行匹配的值,pattern是匹配模式,guardCondition是守卫条件(一个布尔表达式),result是当该case分支匹配成功时返回的结果
package matchcase
/*value match {
case pattern if 条件=> result
// 其他case语句...
}
*/
object matchcase07 {
def main(args: Array[String]): Unit = {
val a = 11
a match {
case x: Int if a > 10 => println("a是大于10的Int")
case _ => println("a is not Int")
}
}
}
(三)案例-判断星座
目标任务,编写一个函数,参数是月份和日期,返回值是当前的星座。
package matchcase
object matchcase08 {
// 自己根据12星座写
def getZodiac(month: Int, day: Int): String = {
month match {
case 1 if day >= 20 => "水瓶座" // 月份是1, 并且日期 >= 20的
case 2 if day <= 18 => "水瓶座"
case 2 if day >= 19 => "双鱼座"
case 3 if day <= 20 => "双鱼座"
case 3 if day >= 21 => "白羊座"
case 4 if day <= 19 => "白羊座"
case 4 if day >= 20 => "金牛座"
case 5 if day <= 20 => "金牛座"
case 5 if day >= 21 => "双子座"
case 6 if day <= 21 => "双子座"
case 6 if day >= 22 => "巨蟹座"
case 7 if day <= 22 => "巨蟹座"
case 7 if day >= 23 => "狮子座"
case 8 if day <= 22 => "狮子座"
case 8 if day >= 23 => "处女座"
case 9 if day <= 22 => "处女座"
case 9 if day >= 23 => "天秤座"
case 10 if day <= 22 => "天秤座"
case 10 if day >= 23 => "天蝎座"
case 11 if day <= 21 => "天蝎座"
case 11 if day >= 22 => "射手座"
case 12 if day <= 21 => "射手座"
case 12 if day >= 22 => "摩羯座"
case 1 if day <= 19 => "摩羯座"
case _ => "未知"
}
}
def main(args: Array[String]): Unit = {
println(getZodiac(1, 19))
println(getZodiac(1, 23)) // 水瓶座
}
}