match case 的基本格式

29 阅读1分钟

match case 匹配匹配

  1. 匹配元组不同的元素的数量
  2. 匹配数组特殊值
  3. 匹配变量的类型

match case 案例匹配

  1. 匹配样例类(属性值)

image.png

object case05 {
  /*
    match case 高阶匹配
    1. 匹配元组不同的元素的数量
    2. 匹配数组特殊值
    3. 匹配类型的变量
    4. 匹配样例类(属性值)
   */

  // 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))
  }
}
```
```