scala模式匹配-基础使用1.3

26 阅读1分钟

高阶匹配之匹配元素特征

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

例如如下的格式:

数组 match {

case Array(1,x,y) => 匹配到数组,长度为3,且第一个元素为1

case Array(0) =>匹配到数组:长度为1,且只有一个元素0
case Array(1,_*) =>匹配到数组:长度为n,第一个元素为1

    case _ => 其他

}

package matchcase
object case04 {
  /*
   match case 高阶匹配
   1. 匹配元组不同的元素的数量
   2. 匹配数组特殊值
   3. 匹配变量的类型

   *
   a:Int = 1;
   */

    def matchType(value:Any):Unit = {
      value match {
        case x:Int => println(s"$x 是Int")
        case x:Double => println(s"$x 是Double")
        case _ => println("未知")
      }
    }

    def main(args: Array[String]): Unit = {
      matchType(1)
      matchType(1.1)
    }
  }

高阶匹配之匹配案例类

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

对象 match {

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

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

    case _ => 其他

}

package matchcase

object case05 {
  /*
   match case 高阶匹配
   1. 匹配元组不同的元素的数量
   2. 匹配数组特殊值
   3. 匹配变量的类型
   5. 匹配样例类
   *
   */
  // 1. 圆形类
  case class Circle(radius: Double) {}
  // 2. 矩形类
  case class Rectangle(width: Double, height: Double) {}

  // 封装一个求面积的方法
  def getArea(shape: Any): Double = {
    shape match {
      case Circle(radius) => math.Pi * radius * radius
      case Rectangle(width, height) => width * height
      case _ => 0.0
    }
  }

  def main(args: Array[String]): Unit = {
    // 1. 实例化圆形对象
    val circle = Circle(2.0)
    // 2. 实例化矩形对象
    val rectangle = Rectangle(2.0, 3.0)

    println(getArea(circle))
    println(getArea(rectangle))
    }
  }

当传入Circle类型时,匹配case Circle(r)并按照圆的面积公式计算;当传入Rectangle类型时,匹配case Rectangle(w, h)并按照矩形面积公式计算。