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"
相关推荐
じ☆ve 清风°18 分钟前
JavaScript 原型与原型链:深入理解 __proto__ 和 prototype 的由来与关系
开发语言·javascript·原型模式
_r0bin_5 小时前
前端面试准备-7
开发语言·前端·javascript·fetch·跨域·class
zhang98800005 小时前
JavaScript 核心原理深度解析-不停留于表面的VUE等的使用!
开发语言·javascript·vue.js
Fanxt_Ja7 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法
萌新小码农‍7 小时前
Spring框架学习day7--SpringWeb学习(概念与搭建配置)
学习·spring·状态模式
蓝婷儿7 小时前
6个月Python学习计划 Day 15 - 函数式编程、高阶函数、生成器/迭代器
开发语言·python·学习
行云流水剑7 小时前
【学习记录】深入解析 AI 交互中的五大核心概念:Prompt、Agent、MCP、Function Calling 与 Tools
人工智能·学习·交互
love530love7 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
一弓虽7 小时前
zookeeper 学习
分布式·学习·zookeeper
苗老大7 小时前
MMRL: Multi-Modal Representation Learning for Vision-Language Models(多模态表示学习)
人工智能·学习·语言模型