scala基础学习-匹配模式

文章目录

匹配模式

类似if else elif 又一个分支满足直接结束

默认值 _

使用_作为默认值匹配

scala 复制代码
var i = 6
val day = i match {
  case 0 => "Sunday"
  case 1 => "Monday"
  case 2 => "Tuesday"
  case 3 => "Wednesday"
  case 4 => "Thursday"
  case 5 => "Friday"
  case 6 => "Saturday"
  case _ => "invalid day"   // the default, catch-all 默认值
}
//"invalid day"

变量接受

如果使用变量接收,那么当你匹配不到时,这个变量会接受匹配值,小写

scala 复制代码
i = 9
i match {
  case 0 => println("1")
  case 1 => println("2")
  case what => println(s"You gave me: $what")
}

变量引用

在模式中使用的名称必须以小写字母开头。 以大写字母开头的名称并不引入变量,而是匹配该范围内的一个值

scala 复制代码
val N = 42
i match {
  case 0 => println("1")
  case 1 => println("2")
  case N => println("42")  //引入的变量
  case n => println(s"You gave me: $n" )  //接受匹配失败的i
}

单case多条件

一条case包含多个匹配条件

scala 复制代码
val evenOrOdd = i match {
  case 1 | 3 | 5 | 7 | 9 => println("odd")
  case 2 | 4 | 6 | 8 | 10 => println("even")
  case _ => println("some other number")
}

if守卫

case 子句中使用 if 守卫

scala 复制代码
i= -1
i match {
  case 1 => println("one, a lonely number")
  case x if x % 2 == 0 || x == 3 => println("two's company, three's a crowd") //x接受i值 判断
  case x if x > 3 => println("4+, that's a party")
  case _ => println("i'm guessing your number is zero or less")
}

数组范围匹配

与数字范围匹配,a,b,c效果一直都是接受i 2025资料分析理论实战讲义(第三周).pdf

scala 复制代码
i = 19
i match {
  case a if 0 to 9 contains a => println(s"0-9 range: $a")  
  case b if 10 to 19 contains b => println(s"10-19 range: $b")
  case c if 20 to 29 contains c => println(s"20-29 range: $c")
  case _ => println("Hmmm...")
}

样例类和 match 表达式

您还可以从 case 类中提取字段 ------ 以及正确编写了 apply/unapply 方法的类 ------ 并在守卫条件下使用这些字段。 下面是一个使用简单 Person 案例类的示例:

scala 复制代码
case class Person(name: String)

def speak(p: Person) = p match {
  case Person(name) if name == "Fred" => println(s"$name says, Yubba dubba doo")
  case Person(name) if name == "Bam Bam" => println(s"$name says, Bam bam!")
  case _ => println("Watch the Flintstones!")
}

speak(Person("Fred"))      // "Fred says, Yubba dubba doo"
speak(Person("Bam Bam"))   // "Bam Bam says, Bam bam!"

有许多不同形式的模式可用于编写 match 表达式。 示例包括:

  • 常量模式(如 case 3 =>
  • 序列模式(如 case List(els : _*) =>
  • 元组模式(如 case (x, y) =>
  • 构造函数模式(如 case Person(first, last) =>
  • 类型测试模式(如 case p: Person =>

所有这些类型的模式匹配都展示在以下 pattern 方法中,该方法采用类型为 Matchable 的输入参数并返回 String

scala 复制代码
def pattern(x: Matchable): String = x match {

  // constant patterns
  case 0 => "zero"
  case true => "true"
  case "hello" => "you said 'hello'"
  case Nil => "an empty List"

  // sequence patterns
  case List(0, _, _) => "a 3-element list with 0 as the first element"
  case List(1, _*) => "list, starts with 1, has any number of elements"
  case Vector(1, _*) => "vector, starts w/ 1, has any number of elements"

  // tuple patterns
  case (a, b) => s"got $a and $b"
  case (a, b, c) => s"got $a, $b, and $c"

  // constructor patterns
  case Person(first, "Alexander") => s"Alexander, first name = $first"
  case Dog("Zeus") => "found a dog named Zeus"

  // type test patterns
  case s: String => s"got a string: $s"
  case i: Int => s"got an int: $i"
  case f: Float => s"got a float: $f"
  case a: Array[Int] => s"array of int: ${a.mkString(",")}"
  case as: Array[String] => s"string array: ${as.mkString(",")}"
  case d: Dog => s"dog: ${d.name}"
  case list: List[?] => s"got a List: $list"
  case m: Map[?, ?] => m.toString

  // the default wildcard pattern
  case _ => "Unknown"
相关推荐
Aotman_39 分钟前
JS 按照数组顺序对对象进行排序
开发语言·前端·javascript·vue.js·ui·ecmascript
Mabnus41 分钟前
细胞骨架协调蛋白VIM
学习
方璧8 小时前
限流的算法
java·开发语言
Hi_kenyon8 小时前
VUE3套用组件库快速开发(以Element Plus为例)二
开发语言·前端·javascript·vue.js
曲莫终8 小时前
Java VarHandle全面详解:从入门到精通
java·开发语言
xiaobai1788 小时前
测试工程师入门AI技术 - 前序:跨越焦虑,从优势出发开启学习之旅
人工智能·学习
北岛寒沫8 小时前
北京大学国家发展研究院 经济学原理课程笔记(第二十一课 金融学基础)
经验分享·笔记·学习
扑火的小飞蛾9 小时前
网络安全小白学习路线图 (基于提供文档库)
学习·安全·web安全
ghie90909 小时前
基于MATLAB GUI的伏安法测电阻实现方案
开发语言·matlab·电阻