一. scala 模式匹配(pattern matching)

pattern matching 可以说是 scala 中十分强大的一个语言特性,当然这不是 scala 独有的,但这不妨碍它成为 scala 的语言的一大利器。

scala 的 pattern matching 是类似这样的,

e match {
case Pattern1 => do Something
case Pattern2 if-clause => do others
...
}

其中,变量 e 后面接一个 match 以及一个代码块,其中每个 case 对应一种可能回匹配的类型,如果匹配成功则执行 => 后面的代码。

我们可以用一个具体一些的例子来看看模式匹配是怎么工作的:

case class Player(name: String, score: Int)
def printMessage(player: Player) = player match {
case Player(_, score) if score > 100000 =>
println("Get a job, dude!")
case Player(name, _) =>
println("Hey, $name, nice to see you again!")
}

看起来有点类似于其他语言的 switch,但其实还是有很大的不同的。

以java 的 switch 为例,java 的 switch 仅仅会做一些基本类型的匹配,然后执行一些动作,并且是没有返回值的。

而 scala 的 pattern matching match 则要强大得多,除了可以匹配数值,同时它还能匹配类型。

def parseArgument(arg: String) = arg match {
//匹配值
case "-h" | "--help" => displayHelp
case "-v" | "--version" => displayVerion
case whatever => unknownArgument(whatever)
}
def f(x: Any): String = x match {
//匹配类型
case i:Int => "integer: " + i
case _:Double => "a double"
case s:String => "I want to say " + s
}

同时 pattern matching 是有返回值的,比如上面的 match ,它返回的就是一个 Unit。我们也可以修改上面的代码让它返回一个字符串:

case class Player(name: String, score: Int)
def message(player: Player) = player match {
case Player(_, score) if score > 100000 =>
"Get a job, dude!"
case Player(name, _) =>
"Hey, $name, nice to see you again!"
}

值得一提的是, pattern matching 返回值是由第一个匹配的模式中的代码块决定的。

二. 为什么要用 pattern matching

看到这里你会发现一个问题, pattern matching 不是和if else 差不多吗?那为什么还要使用 pattern matching 呢?

首先我们需要明白,模式匹配其实本质上是提供一个方便的解构 (Destructuring) 数据结构的方式,以 scala 为例, pattern matching 其实用到了 scala 中提取器的功能, 提取器其实就是类中的 unapply () 方法。

trait User {
def name: String
}
class FreeUser(val name: String) extends User
object FreeUser {
//提取器
def unapply(user: FreeUser): Option[String] = Some(user.name)
}
  val user: User = new FreeUser("Daniel")
user match {
case FreeUser(name) => println("it match here" + name)
case _ => println("not me")
}

明白了模式匹配的本质你就会直到,其实 if else 只是 pattern matching 中的一个典型的用法,但并非它的全部。

同时, pattern matching 允许你解耦两个并不真正属于彼此的东西,也使得你的代码更易于测试。比如上面的 match 部分的代码我们可以写成下面这样:

  val user: User = new FreeUser("Daniel")
//将返回结果存在一个常量中
val message = user match {
case FreeUser(name) => "it match here" + name
case _ => "not me"
}
//可以随意使用该常量,实现解耦
println(message)

这样会赋予代码更多的灵活性,同时也更加方便做进一步操作。

而以可读性的角度来说,使用一大堆的 if else 代码无疑是比较难看的,而如果使用 pattern matching 的话,代码会简洁清晰很多,而简洁的代码则会更容易阅读。

原文链接
本文为云栖社区原创内容,未经允许不得转载。

聊聊 scala 的模式匹配的更多相关文章

  1. 【scala】模式匹配

    Scala的模式匹配是通过match表达式从若干可选项中选择,类似Java中的switch. 例子: val firstArg = if(args.length>0) args(0) else ...

  2. Scala之模式匹配(Patterns Matching)

    前言 首先.我们要在一開始强调一件非常重要的事:Scala的模式匹配发生在但绝不仅限于发生在match case语句块中.这是Scala模式匹配之所以重要且实用的一个关键因素!我们会在文章的后半部分具 ...

  3. scala 常用模式匹配类型

    模式匹配的类型 包括: 常量模式 变量模式 构造器模式 序列模式 元组模式 变量绑定模式等. 常量模式匹配 常量模式匹配,就是在模式匹配中匹配常量 objectConstantPattern{ def ...

  4. Scala学习——模式匹配

    scala模式匹配 1.基础match case(类似java里switch case,但功能强大些) object MatchApp { def main(args: Array[String]): ...

  5. Scala的模式匹配

    1.概述 2.程序示例(普通的示例) 3.模式匹配(Array) 4.程序示例(Array) 5.模式匹配(List) 6.程序示例 7.遍历 8.模式匹配(case class) 9.程序示例(传统 ...

  6. 聊聊 Scala 的伴生对象及其意义

    2019-04-22 关键字:Scala 伴生对象的作用 关于 Scala 伴生对象,比教材更详细的解释. 什么是伴生对象? 教材中关于伴生对象的解释是:实现类似 Java 中那种既有实例成员又有静态 ...

  7. Scala入门系列(十一):模式匹配

    引言 模式匹配是Scala中非常有特色,非常强大的一种功能. 类似于Java中的switch case语法,但是模式匹配的功能要比它强大得多,switch只能对值进行匹配,但是Scala的模式匹配除了 ...

  8. Scala - 快速学习07 - 模式匹配

    Scala中的模式匹配的功能可以应用到switch语句.类型检查.“解构”等多种场合. 简单匹配 Scala的模式匹配最常用于match语句中.Scala的match语句类似Java里的switch. ...

  9. Scala学习教程笔记三之函数式编程、集合操作、模式匹配、类型参数、隐式转换、Actor、

    1:Scala和Java的对比: 1.1:Scala中的函数是Java中完全没有的概念.因为Java是完全面向对象的编程语言,没有任何面向过程编程语言的特性,因此Java中的一等公民是类和对象,而且只 ...

随机推荐

  1. Ubuntu全盘备份与恢复,亲自总结,实测可靠

    https://blog.csdn.net/sinat_27554409/article/details/78227496 Ubuntu全盘备份与恢复,亲自总结,实测可靠 初学者在使用Ubuntu这类 ...

  2. cadence布线完成后的补充操作

    完成布线之后,需要生成光绘文件和钻孔文件,在生成钻孔文件之前,还有几点补充!

  3. PIL成就你的自信之路

    1.强大的PIL库 在Python中,有一个优秀的图像处理框架,就是PIL库,本博文会分模块,介绍PIL库中的各种方法,并列举相关例子. 学习总结:PIL库可以让我们得到更多的需求,以此来满足我们的需 ...

  4. CSS面试细节整理(二)

    5.css盒模型: CSS 框模型 (Box Model) 规定了元素框处理元素内容.内边距.边框 和 外边距 的方式

  5. OJ002

    register:这个关键字请求编译器尽可能的将变量存在CPU内部寄存器中,而不是通过内存寻址访问,以提高效率.注意是尽可能,不是绝对. 因为,如果定义了很多register变量,可能会超过CPU的寄 ...

  6. Android单元测试之二:本地测试

    Android单元测试之二:本地测试 本地测试 本地测试( Local tests):只在本地机器 JVM 上运行,以最小化执行时间,这种单元测试不依赖于 Android 框架,或者即使有依赖,也很方 ...

  7. [Swift]LeetCode153. 寻找旋转排序数组中的最小值 | Find Minimum in Rotated Sorted Array

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

  8. [Swift]LeetCode397. 整数替换 | Integer Replacement

    Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If ...

  9. [Swift]LeetCode699. 掉落的方块 | Falling Squares

    On an infinite number line (x-axis), we drop given squares in the order they are given. The i-th squ ...

  10. [Swift]LeetCode915.将分区数组分成不相交的间隔 | Partition Array into Disjoint Intervals

    Given an array A, partition it into two (contiguous) subarrays left and right so that: Every element ...