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"
相关推荐
蜡笔弄丢了小新4 分钟前
qt之Vertical Layout
开发语言·qt
laimaxgg5 分钟前
Qt常用控件之微调框QSpinBox
开发语言·c++·qt·qt5·qt6.3
傻啦嘿哟8 分钟前
如何配置HTTP代理及SOCKS代理的工作原理
开发语言·php
一天八小时11 分钟前
HTTP学习——————(四)TLS等加密算法
网络协议·学习·http
weixin_5025398541 分钟前
rust学习笔记7-344. 反转字符串
笔记·学习
hzj61 小时前
极简Redis速成学习
数据库·redis·学习
kikikidult1 小时前
OpenGL 04--GLSL、数据类型、Uniform、着色器类
c++·笔记·学习·opengl
西瓜拍两瓣1 小时前
深入理解Java并发编程(一):揭秘并发性能优化的底层机制
java·开发语言·jvm·笔记·性能优化
卷卷的小趴菜学编程2 小时前
linux第四讲----基础开发工具vim
linux·运维·服务器·c语言·开发语言
Code成立2 小时前
《深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)》
java·开发语言·jvm