模式匹配-基础使用2

55 阅读2分钟

match case 高阶匹配

(一)

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

格式:

def processValue(value: Any): Unit =
value match {
    case i: Int => println(s"这是一个整数:$i")
    case d: Double => println(s"这是一个双精度浮点数:$d")
    case s: String => println(s"这是一个字符串:$s")
    case b: Boolean => println(s"这是一个布尔值:$b")
    case _ => println("这是其他类型")
}  
}  
matchType(5)  
matchType("Hello")

代码示例:

object case01 {
    /*
     * 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)
    }
}

(二)

  1. 匹配元组不同的元素的数量
  2. 匹配数组特殊值
  3. 匹配变量的类型
  4. 匹配样例类(属性值)
object case02 {
  // 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))
  }
}

高阶匹配之匹配案例类

object case03 {
    // 1. for 循环中,做匹配。
    def main(args: Array[String]): Unit = {
      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)
      }

      // m1.foreach{
      //   case (key,value)=>{
      //     if(value == 1983)
      //       println(key)
      //   }
      // }
    }
}
object case04 {
    def main(args: Array[String]): Unit = {
      // 定义一个数组,其中有6个元素
      val arr = Array(1, 22, 33, 4, 5, 6)

      // 需求: 补充定义三个元素 x,y,z,分别保持原arr中的第1,2,3个元素的值
      // var x = arr(0)
      // var y = arr(1)
      // var z = arr(2)
      // println("x="+x + ",y="+ y + ",z="+ z)

      // 优化: 使用match case模式匹配,完成上述需求
      val Array(x, y, z, _*) = arr
      println("x=" + x + ",y=" + y + ",z=" + z)
    }
}