模式匹配基本使用

2 阅读1分钟
object case04 {
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)
//  1. 圆形类
case class Circle(radius: Double)  {}
//  2.矩形类
case class Rectang(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.实例化矩形对象