模式匹配-基本使用(2)

44 阅读1分钟

设计一个面积计算方法,要求能计算矩形的同时能计算正方形

代码:

case class Circle(radius: Double) {}
  case class Rectangle(width: Double, height: Double) {}

  def getArea(shape:Any):Unit = {
        shape match {
      case Circle(radius) => math.Pi * radius *radius
      case Rectangle(width,height) => width * height
      case _ => 0.0
  }
}

  def main (args: Array[String]): Unit = {

    val circle = Circle(2.0)
    val rectangle = Rectangle(2.0,3.0)

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

设计一个方法,要求能匹配输出的变量类型

代码:

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

设计一个方法,要求能根据map中的某一个信息匹配出完整的信息

代码:

val m1 = Map(
  "马云 - 阿里巴巴" -> 1964,
  "张一鸣 - 字节跳动" -> 1983,
  "刘强东 - 京东" -> 1974,
  "程维 - 滴滴" -> 1983
)
// 请在m1这个map,找出所有1983年出生的企业家

for((key,1983) <- m1){
  println(key)
}

for((key,value) <- m1){
  if(value == 1983)
    println(key)
}