(三十三)模式匹配-基础使用

27 阅读3分钟

(一)分析问题并解决

根据一个值输出另一个与之对应的值,很容易就想到if else

package matchcase

object matchcase01 {
  def main(args: Array[String]): Unit = {
    println(getProvinceName(43))
    println(getProvinceName(42))
    println(getProvinceName(12))
  }

  def getProvinceName(code:Int):String = {
    code match {
      case 43 => "湖南"
      case 42 => "湖北"
      case 11 => "北京"
    }
  }

}

(二)高阶匹配之元组元素数量

前面的匹配都是精准匹配:变量和值是相等的。但是呢,scala中的模式匹配的规则是非常强大的,不一定是精准的匹配值,还可以根据元组的元素的个数来匹配。

package matchcase
/*
match case 相当于 if else if 这种分支选择结构,精确匹配值
// 1. case _ 是不匹配的:如果匹配不成功,只没case _ 程序会报错
// 2. case _ 必须要放在最后
// 匹配后面元组中的元素个数:a = +
// 匹配后面元组中的元素个数:a = +
*/
object matchcase02 {
  def main(args: Array[String]): Unit = {
    val xiaohong = (100,100,100)
    val xiaoming = (60,80)
    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
/*
(3)匹配变量类型
*/
object matchcase03 {
  def main(args: Array[String]): Unit = {
    testType(1)
    testType(1.1)
    testType("1")
  }

  def testType(i:Any):Unit = {
    i match {
      case _:Int => println("当前变量是: Int")
      case _:Double => println("当前变量是: Double")
      case _ => println("未知")
    }
  }
}

注意:如果变量名没有被使用到,可以使用_代替。

(四)高阶匹配之匹配元素特征

模式匹配还可以根据数组元素的个数,元素的特征来匹配。

package matchcase

/*
(3)匹配元素特征
*/
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("未知")
    }
  }
}

(五)高阶匹配之匹配案例类

模式匹配还根据案例类的不同,匹配不同的案例类和其中的字段信息。 例如格式

对象 match {

case 样例类类型1(字段1,字段2)=> 表达式

case 样例类类型2(字段1,字段2,字段3)=> 表达式

case _ => 其他

package matchcase

// match case 的用法
/*
* (1)类似于 if else if 这种分支选择结构,精确匹配值
* // 1. case _ 是不可省略的:如果匹配不成功,又没case _ 程序会报错
* // 2. case _ 必须要放在最后。
* (2)匹配后面元组的元素个数
* (3)匹配变量类型
* (4)匹配元素特征
* (5)样例类模式匹配
*/
object matchcase05 {
  // case class 案例类: 圆,它有一个属性:半径
  case class Circle(radius:Double)
  // case class 样例类: 矩形,它有两个属性:长和宽
  case class Rectangle(width:Double, height:Double)

  // 定义一个方法,用来求shape的面积
  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")
  }
}