大数据学习之Scala——07模式匹配
发布日期:2021-05-06 17:19:27 浏览次数:21 分类:技术文章

本文共 2533 字,大约阅读时间需要 8 分钟。

一. 基础

1. 基本介绍
  1. 模式匹配语法中,采用match关键字声明,每个分支采用case关键字进行声明
  2. 当需要匹配时,会从第一个case分支开始,如果匹配成功,那么执行对应的逻辑代码,如果匹配不成功,继续执行下一个分支进行判断。
  3. 如果所有case都不匹配,那么会执行case _ 分支,类似于Java中default语句。
2. 案例
  • print("输入第1个数: ")val n1 = StdIn.readDouble()print("输入运算符: ")val oper = StdIn.readChar()print("输入第2个数: ")val n2 = StdIn.readDouble()var res: Double = 0oper match {
    case '+' => res = n1 + n2 case '-' => res = n1 - n2 case '*' => res = n1 * n2 case '/' => res = n1 / n2 case _ => println("oper error")}println(s"$n1 $oper $n2 = $res")
3. 注意事项
  1. 如果所有case都不匹配,那么执行case _ 分支,类似于Java中default语句
  2. 如果所有case都不匹配,又没有写case _ 分支,那么会抛出MatchError
  3. 每个case中,不用break语句,自动中断case
  4. 可以在match中使用其它类型,而不仅仅是字符,可以是表达式
  5. => 类似于 java swtich 的 :
  6. => 后面的代码块到下一个case, 是作为一个整体执行,可以使用{} 括起来,也可以不括。

二. 匹配

1. 类型匹配

1. 基本介绍
  1. 可以匹配对象的任意类型,这样做避免了使用isInstanceOf和asInstanceOf方法
2. 案例
  • val a = 4val obj =  if(a == 1) 1  else if(a == 2) "2"  else if(a == 3) BigInt(3)  else if(a == 4) Map("aa" -> 1)  else if(a == 5) Map(1 -> "aa")  else if(a == 6) Array(1, 2, 3)  else if(a == 7) Array("aa", 1)  else if(a == 8) Array("aa")val result = obj match {
    case _ : Int => "类型为: Int" case _ : String => "类型为: String" case _ : Map[String, Int] => "类型为: Map[String, Int]" case _ : Map[Int, String] => "类型为: Map[Int, String]" case _ : Array[String] => "类型为: Array[String]" case _ : Array[Int] => "类型为: Array[Int]" case _ : BigInt => "类型为: BigInt" case _ => "啥也不是"}println(result)
    在这里插入图片描述
3. 注意事项:
  1. Map[String, Int] 和Map[Int, String]是两种不同的类型,其它类推。

  2. 在进行类型匹配时,编译器会预先检测是否有可能的匹配,如果没有则报错.

    val obj = 10val result = obj match {
    case a : Int => a // 报错: 因为obj不可能匹配成功 case b : Map[String, Int] => "Map集合" case _ => "啥也不是"}

2. 匹配数组

1. 基本介绍
  1. Array(0) 匹配只有一个元素且为0的数组。
  2. Array(x,y) 匹配数组有两个元素,并将两个元素赋值为x和y。当然可以依次类推Array(x,y,z) 匹配数组有3个元素的等等…
  3. Array(0,_*) 匹配数组以0开始
2. 案例
  • for (arr <- Array(Array(0), Array(1), Array(1, 0),   Array(0, 1, 0), Array(1, 1, 0), Array(1, 1, 0, 1))) {
    val result = arr match {
    // 数组 0 case Array(0) => "0" // 两个元素的数组 case Array(x, y) => x + "=" + y // 第一个元素是0的数组 case Array(0, _*) => "以0开头和数组" case _ => "什么集合都不是" } println("result = " + result)}
    在这里插入图片描述

3. 匹配列表

1. 基本介绍
  1. 0 :: Nil : 匹配列表0
  2. x :: y :: Nil : 匹配两个元素的列表
  3. 0 :: tail : 匹配0开头的列表
2. 案例
  • for (list <- Array(List(0), List(5, 5), List(0, 1, 0), List(1, 0, 0))) {
    val result = list match {
    // 列表0 case 0 :: Nil => "0" // 两个元素的列表 case x :: y :: Nil => x + " " + y // 以0开头的列表 case 0 :: tail => "0 ..." // 其他 case _ => "something else" } println(result)
    在这里插入图片描述

声明:

  1. 本文参考了尚硅谷Scala课程的课件
上一篇:大数据学习之Spark——00Spark项目的pom.xml文件
下一篇:大数据学习之Scala——06集合

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年03月20日 07时29分04秒