一、match case的基本格式
执行流程是:如果value匹配到了pattern1,就执行结果1
如果都没有匹配到,就执行 _ 对应的内容。
- 1.如果能精准匹配成功,就会执行后面的代码
- 2.case _ 他表示可以匹配任意的内容。一定要放在match case的最后一条
- 3.case _ 不能省略:如果匹配不成功,就会报错
代码演示:
object matches01 {
// 42 -> 湖北省
// 52 -> 四川省
def main(args: Array[String]): Unit = {
// val code = 52
// var province = ""
// if(code == 42) {
// province = "湖北省"
// } else if (code == 52) {
// province = "四川省"
// } else {
// province = "未知"
// }
// println(province)
val code = 12
val province = code match {
case 42 => "湖北省"
case 52 => "四川省"
case _ => "未知"
}
println(province)
}
}
二、match case
-
1.匹配精确值
object matches02 {
def main(args: Array[String]): Unit = {
// 输入1,输出单词one
// 输入2,输出单词two
// 输入3,输出单词three
// 输入其他,输出单词other
// 1.从键盘获取数字
val code = 10
// 2.使用matchase进行匹配
code match {
case 1 => println("one")
case 2 => println("two")
case _ => println("other")
}
}
}
-
2.匹配数据类型
object matches03 {
def processValue(value:Any): Unit = {
value match {
case x : Int => println("Int")
case x : String => println("String")
case _ => println("Other")
}
}
def main(args: Array[String]): Unit = {
val obj = 10
processValue(obj)
}
}
-
3.匹配元素个数
object matches03 {
def processNum(value:Any): Unit = {
value match {
case (a,b,c) => println("三个元素的元组")
case (x,y) => println("两个元素的元组")
case _ => println("其他")
}
}
def main(args: Array[String]): Unit = {
processNum( (1,2) )
processNum( (1,2,3) )
}
}
-
4.匹配数组个数,元素特征
object matches04 {
def matchArray(arr:Any): Unit = {
arr match {
case Array(x,y) => println("匹配到有两个元素的数组",x,y)
case Array(1,b,c) => println("匹配到有三个元素的数组,第一个元素是1")
case Array(a,b,c) => println("匹配到有三个元素的数组",a,b,c)
case Array(10,_*) => println("第一个元素是10,元素的个数有任意个")
case _ => println("没有匹配到")
}
}
def main(args: Array[String]): Unit = {
val arr1 = Array(1,2,3)
val arr2 = Array(2,2,3)
val arr3 = Array(10,2,3,4)
matchArray(arr1)
matchArray(arr2)
matchArray(arr3)
}
}
-
5.匹配案例类
object matches05 {
case class Circle(r:Double)
case class Rectangle(w: Double, h: Double)
def calculateArea(shape:Any): Double = {
shape match {
case Circle(r) => 3.14 * r * r
case Rectangle(w,h) => w * h
case _ => 0.0
}
}
def main(args: Array[String]): Unit = {
val circle = Circle(2.0)
val rectangle = Rectangle(2.0, 3.0)
println(calculateArea(circle))
println(calculateArea(rectangle))
}
}
-
6.变量声明时的匹配
object matches06 {
def main(args: Array[String]): Unit = {
val arr = Array(11, 22, 33, 4, 5)
// 定义三个变量:x y z 保存数组中的前三个元素的值
// val x = arr(0)
// val y = arr(1)
// val z = arr(2)
val Array(x, y, z, _*) = arr
println(x, y, z)
}
}