内容:
1.Scala 中的模式匹配
(一)问题导入
我们今天接到一个开发任务,就是根据身份证号码,输出这个人的籍贯。例如:42表示湖北,33表示浙江,11表示北京,31表示上海。
(二)具体代码
scala
package matchcase
/**
match case
三大结构
1. 顺序结构
2. 选择结构
(1) if, if else if else;
(2) match case
case_ 不能省略,否则,匹配失败会报错
case_ 必需写在最后
3. 循环结构:
(1) for
(2) while, do...while
* */
object case01 {
def main(args: Array[String]): Unit = {
// val code = "11"
// var province = ""
//
// if(code == "42"){
// province = "湖北"
// } else if(code == "11") {
// province = "北京"
// } else {
// province = "未知"
// }
val code = "11"
val province = code match {
case "42" => "湖北"
case "11" => "北京"
case _ => "未知"
}
println(s"${code} 对应的省份是:${province}")
}
}
【运行结果】 
(三)match case的基本格式
格式如下:
scala
value match {
case pattern1 => result1
case pattern2 => result2
...
case patternN => resultN
case _ => 其他
}
执行流程是:如果value匹配到了pattern1,就执行结果1,如果都没有匹配到,就执行 _ 对应的内容。
通过例子来巩固下:
输入一个1~5的数字,打印它对应的英语单词
scala
package matchcase
object case02 {
def main(args: Array[String]): Unit = {
// 输入一个1~5的数字,打印它对应的英语单词
val num = 2
val word = num match {
case 1 => "One"
case 2 => "Two"
case 3 => "Three"
case 4 => "Four"
case 5 => "Five"
case _ => "Other"
}
println(s"${num} 对应的英文是:${word}")
}
}
【运行结果】 
(四)高阶匹配之元组元素数量
前面的匹配都是精准匹配:变量和值是相等的。但是呢,scala中的模式匹配的规则是非常强大的,不一定是精准的匹配值,还可以根据元组的元素的个数来匹配。
scala
package matchcase
/*
* match case 高阶匹配
* 1.匹配元组不同的元素的数量
*
*
* */
object case03 {
def main(args: Array[String]): Unit = {
// 元组
val t1 = (2,3)
t1 match {
case (a,b) => println(s"有二个元素${a},${b}")
case _ => println("未知")
}
val arr1 = Array(10,2)
arr1 match {
case Array(1,x,y) => println("数组,第一个元素是1,长度为3")
case Array(10,x) => println("数组,第一个元素是10,长度为2")
case _ => println("其他")
}
}
}
【运行结果】 