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"
相关推荐
笑口常开xpr几秒前
【C++继承】深入浅出C++继承机制
开发语言·数据结构·c++·算法
还是大剑师兰特2 分钟前
Scala面试题及详细答案100道(71-80)-- 与Java的交互
scala·大剑师·scala面试题
molong9318 分钟前
Activity/Service/Broadcast/ContentProvider 生命周期交互
android·学习·交互
楼田莉子14 分钟前
python学习:爬虫+项目测试
后端·爬虫·python·学习
你不是我我24 分钟前
【Java开发日记】请介绍类加载过程,什么是双亲委派模型?
java·开发语言
嘉年华-cocos29 分钟前
高中3500个单词, 纯粹数据版, 助力背诵, 按相似度+从短到长 排序
学习·英语·背单词·音标·记单词
teeeeeeemo33 分钟前
Webpack 模块联邦(Module Federation)
开发语言·前端·javascript·笔记·webpack·node.js
东风西巷1 小时前
draw.io(免费流程图制作工具) 中文绿色版
学习·电脑·流程图·软件需求·draw.io
修炼室1 小时前
如何将Python脚本输出(含错误)全量保存到日志文件?实战指南
开发语言·python
@LetsTGBot搜索引擎机器人1 小时前
用 Python 打造一个 Telegram 二手交易商城机器人
开发语言·python·搜索引擎·机器人·.net·facebook·twitter