(一)match case的基本格式
value match {
case pattern1 => result1
case pattern2 => result2
...
case patternN => resultN
case _ => 其他
}
执行流程是:如果value匹配到了pattern1,就执行结果1,如果都没有匹配到,就执行 _ 对应的内容。
package matchcase
object matchcase01 {
def main(args: Array[String]): Unit = {
println(getProvinceName(11))
println(getProvinceName(42))
println(getProvinceName(12))
}
def getProvinceName(code: Int): String = {
code match {
case 42 => "湖北"
case 11 => "北京"
case _ => "未知"
}
}
}
(二)高阶匹配之元组元素数量
package matchcase
object matchcase02 {
def main(args: Array[String]): Unit = {
val xiaohong = (100,100,100)
val xiaoming = (99,98)
getScore(xiaohong)
getScore(xiaoming)
getScore(1,2,3,4)
}
def getScore(score:Any):Unit = {
score match {
case (a,b,c) => println(s"元组中有三个元素: a = $a b = $b c = $c")
case (a,b) => println(s"元组中有两个元素: a = $a b = $b")
case _ => println("未知")
}
}
}
(三)高阶匹配之匹配元素特征
package matchcase
object matchcase04 {
def main(args: Array[String]): Unit = {
testType(Array(1,2,3))
testType(Array(1,2,3,4))
testType(Array(11,2,3,4))
testType(Array(11,1,3,4))
}
def testType(arr:Any):Unit = {
arr match {
case Array(1, x, y) => println("arr是一个数组,有三个元素,第一个是1")
case Array(1, x, y, z) => println("arr是一个数组,有四个元素,第一个是1")
case Array(x, 1, y, z) => println("arr是一个数组,有四个元素,第二个是1")
case _ => println("未知")
}
}
}
(四)高阶匹配之变量类型匹配
package matchcase
object matchcase03 {
def main(args: Array[String]): Unit = {
testType(1)
testType(1.1)
testType("1")
}
def testType(i:Any):Unit = {
i match {
case x:Int => println("当前变量是:Int")
case x:Double => println("当前变量是:Double")
case _ => println("未知")
}
}
}
(五)高阶匹配之匹配案例类
package matchcase
object matchcase05 {
case class Circle(radius:Double)
// 定义一个样例类:矩形。它有两个属性:长和宽
case class Rectangle(width:Double,height:Double)
// 定义一个方法,用来求图形、矩形的面积
def getArea(obj:Any):Unit = {
obj match {
case Circle(radius) => println("圆形的面积是:" + radius * radius * 3.14)
case Rectangle(width,height) => println("矩形的面积是:" + width * height)
case _ => println("未知")
}
}
def main(args: Array[String]): Unit = {
getArea(Circle(2))
getArea(Rectangle(2,3))
getArea("abc")
}
}