(一)match case的基本格式
match case 的用法
1. case _ 是不可省略的,如果匹配不成功,又没有 case _,程序会报错
2. case _ 必须要放在最后面
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 = (89, 98)
getScore(xiaohong)
getScore(xiaoming)
getScore(1,2, 3, 4)
}
def getScore(score: Any): Unit = {
score match {
case (a, b, c) => println("元组中有三个元素:a=" + a + " b=" + b + " c=" + c)
case (a, b) => println("元组中有两个元素:a=" + a + " b=" + b)
case _ => println("未知")
}
}
}
(三)高阶匹配之变量类型匹配
package matchcase
object matchcase03 {
def main(args: Array[String]): Unit = {
testType(1)
testType(1.0)
testType("1")
}
def testType(i:Any):Unit ={
i match {
case x:Int => println("当前变量是:Int")
case x:Double => println("当前变量是:Double")
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 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.0))
getArea(Rectangle(2.0,3.0))
getArea("abc")
}
}