Scala的sealed关键字

缘起

今天在学习Akka的监控策咯过程中看到了下面一段代码:

  def supervisorStrategy(): SupervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 10 seconds) {
case _: ArithmeticException => Resume
case _: IllegalArgumentException => Restart
case _: NullPointerException => Stop
case _: Exception => Escalate
}

当时有点好奇,就想去看看Resume, Restart等的实现,于是就看到了下面的代码:

object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits {

sealed trait Directive

/**
* Resumes message processing for the failed Actor
*/
case object Resume extends Directive /**
* Discards the old Actor instance and replaces it with a new,
* then resumes message processing.
*/
case object Restart extends Directive /**
* Stops the Actor
*/
case object Stop extends Directive /**
* Escalates the failure to the supervisor of the supervisor,
* by rethrowing the cause of the failure.
*/
case object Escalate extends Directive // ....
}

刚刚Scala不久,不太清楚这里的sealed关键字的作用,本文下面就详细的描述一下这个关键字的作用吧。

模式匹配

模式匹配pattern matching在scala里面是一个重量级的功能,依赖于模式匹配可以优雅地实现很多功能。大致格式如下:

selector match {
pattern1 => <body1>
pattern2 => <body2>
...
}

pattern总结起来大约以下几类:

  • Wildcard patterns // _ 统配
  • Constant patterns // 常量
  • Variable patterns // 变量
  • Constructor patterns // 构造函数
  • Sequence patterns // 比如List(,). 如果需要匹配剩余的话使用List(0,_*)
  • Tuple patterns // (a,b,c)
  • Typed patterns // 使用类型匹配 case a:Map[,]
  • asInstanceOf[]
  • isInstanceOf[]
  • note(dirlt):这里需要注意容器类型擦除.Array例外因为这个是java内置类型

实际上我们还能够使用pattern完成下面事情:

  • Patterns in variable definitions // val (a,b) = ("123","345");

  • Case sequences as partial functions

    • 直接使用pattern来构造函数.以参数为match对象,在body里面直接编写case.
    • Each case is an entry point to the function, and the parameters are specified with the pattern. The body of each entry point is the right-hand side of the case.
  • Patterns in for expressions // for ((country, city) <- capitals)

      // case sequences as partial function.
    val foo : Option[String] => String = {
    case Some(e) => e
    case None => "???"
    } val a = Option[String]("hello")
    println(foo(a))
    val b = None
    println(foo(b))

pattern matching过程中还有下面几个问题需要注意:

  • Patterns are tried in the order in which they are written.
  • Variable binding // 有时候我们希望匹配的变量包含外层结构
    • A(1,B(x)) => handle(B(x))
    • A(1, p @ B(_)) => handle(p) # p绑定了B(x)这个匹配
    • A(1, p @ B()) => handle(p) # B是可以包含unapply从type(p) => Boolean的类,做条件判断
  • Pattern guards // 有时候我们希望对pattern做一些限制性条件
    • A(1,e,e) 比如希望后面两个元素相等,但是这个在pm里面没有办法表达
    • A(1,x,y) if x == y => // 通过guard来完成

scala为了方便扩展模式匹配对象的case, 提供case class这个概念。case class和普通class大致相同,不过有以下三个区别,定义上只需要在class之前加上case即可:

  • 提供factory method来方便构造object

  • class parameter隐含val prefix

  • 自带toString,hashCode,equals实现

      case class A(x:Int) {} // implicit val x:Int
    val a = A(1); // factory method.
    println(a.x);
    println(a); // toString = A(1)

case class最大就是可以很方便地用来做pattern matching.

如果我们能够知道某个selector所有可能的pattern的话,那么就能够在编译期做一些安全性检查。但是selector这个过于宽泛,如果将selector限制在类层次上的话,那么还是可以实现的。举例如下:

abstract class A; // sealed abstract class A
case class B(a:Int) extends A;
case class C(a:Int) extends A;
case class D(a:Int) extends A; val a:A = B(1); a match {
case e @ B(_) => println(e)
case e @ C(_) => println(e)
}

在match a这个过程中,实际上我们可能存在B,C,D三种子类,但是因为我们这里缺少检查。使用sealed关键字可以完成这个工作。sealed class必须和subclass在同一个文件内。A sealed class cannot have any new subclasses added except the ones in the same file. 如果上面增加sealed的话,那么编译会出现如下警告,说明我们没有枚举所有可能的情况。

/Users/dirlt/scala/Hello.scala:8: warning: match may not be exhaustive.
It would fail on the following input: D(_)
a match {
^
one warning found

有三个方式可以解决这个问题,一个是加上对D的处理,一个是使用unchecked annotation, 一个则是在最后用wildcard匹配

    (a : @unchecked)  match {
case e @ B(_) => println(e)
case e @ C(_) => println(e)
} a match {
case e @ B(_) => println(e)
case e @ C(_) => println(e)
case _ => throw new RuntimeException("??");
}

sealed

从上面的描述我们可以知道,sealed 关键字主要有2个作用:

  • 其修饰的trait,class只能在当前文件里面被继承
  • 用sealed修饰这样做的目的是告诉scala编译器在检查模式匹配的时候,让scala知道这些case的所有情况,scala就能够在编译的时候进行检查,看你写的代码是否有没有漏掉什么没case到,减少编程的错误。

Scala的sealed关键字的更多相关文章

  1. C#中sealed关键字

    C#中sealed关键字 1. sealed关键字     当对一个类应用 sealed 修饰符时,此修饰符会阻止其他类从该类继承.类似于Java中final关键字.     在下面的示例中,类 B ...

  2. sealed关键字

    1. sealed关键字    当对一个类应用 sealed 修饰符时,此修饰符会阻止其他类从该类继承.类似于Java中final关键字.    在下面的示例中,类 B 从类 A 继承,但是任何类都不 ...

  3. scala类型系统 type关键字

    和c里的type有点像. scala里的类型,除了在定义class,trait,object时会产生类型,还可以通过type关键字来声明类型. type相当于声明一个类型别名: scala> t ...

  4. C#多态;父类引用指向子类对象;new和override的区别;new、abstract、virtual、override,sealed关键字区别和使用代码示例;c#类的初始化顺序

    关于父类引用指向子类对象 例如: 有以下2个类 public class Father { public int age = 70; public static string name = " ...

  5. scala 使用case 关键字定义类不需要创建对象直接调用

    1.必须是使用case 定义object类 package config import org.apache.spark.sql.SparkSession import org.apache.spar ...

  6. Scala 关键字

    Java关键字 Java 一共有 50 个关键字(keywords),其中有 2 个是保留字,目前还不曾用到:goto 和 const.true.false 和 null 看起来很像关键字,但实际上只 ...

  7. Scala学习之路 (五)Scala的关键字Lazy

    Scala中使用关键字lazy来定义惰性变量,实现延迟加载(懒加载). 惰性变量只能是不可变变量,并且只有在调用惰性变量时,才会去实例化这个变量. 在Java中,要实现延迟加载(懒加载),需要自己手动 ...

  8. Scala基础语法 (一)

    如果你之前是一名 Java 程序员,并了解 Java 语言的基础知识,那么你能很快学会 Scala 的基础语法. Scala 与 Java 的最大区别是:Scala 语句末尾的分号 ; 是可选的. 我 ...

  9. scala(一)Nothing、Null、Unit、None 、null 、Nil理解

    相对于java的类型系统,scala无疑要复杂的多!也正是这复杂多变的类型系统才让OOP和FP完美的融合在了一起! Nothing: 如果直接在scala-library中搜索Nothing的话是找不 ...

随机推荐

  1. javascript: 带分组数据的Table表头排序

    如下图: 要求:点击表头排序时,"分组"及"分组明细"的数据层次关系不变 从网上找了一段常规的table排序,改了改,以满足“分组支持”,贴在这里备份 < ...

  2. 乐易贵宾VIP教程:百度贴吧 - QQ部落 - QQ空间 Post实战系列视频课程

    教程挺不错,3套案例的实战,有需要的可以看一下百度贴吧课程目录:1.百度登录抓包分析2.百度登录[代码实现]3.百度验证码登录[代码实现]4.贴吧关注[抓包分析]5.贴吧关注(代码编写)6.贴吧签到[ ...

  3. 强迫症的福利——我的第一个VS插件,对using排序!

    首先来看看VS自带的using整理功能: 长短不一,看着让人生厌!这是哪个门子的整理?越来越乱了好吗! 难道就没有一款,由短到长——金字塔搬的排序方案吗? 于是各种百度: “VS 插件 using排序 ...

  4. Python3 windows如何安装模块 setuptools

    下载的module解压后里面有setup.py文件,如果打开setup.py文件里面有这段代码: from setuptools import setup ... setup( ... 这种的都需要调 ...

  5. Adobe Reader & PDF 护眼设置

    1.首先选择“编辑”--->“首选项” 选择其他颜色,把RGB如下设置

  6. 面向OPENCL的ALTERA SDK

    面向OPENCL的ALTERA SDK 使用面向开放计算语言 (OpenCL™) 的 Altera® SDK,用户可以抽象出传统的硬件 FPGA 开发流程,采用更快.更高层面的软件开发流程.在基于 x ...

  7. Codeforces Round #370(div 2)

    A B C :=w= D:两个人得分互不影响很关键 一种是f[i][j]表示前i轮,分差为j的方案数 明显有f[i][j]=f[i-1][j-2k]+2*f[i-1][j-2k+1]+...+(2k+ ...

  8. MAC OS上Nginx安装

    admin@admindeMac:local]$ brew install nginx ==> Installing dependencies for nginx: pcre, openssl ...

  9. datePiker弹出框被其他div遮挡

    最近在做项目的时候,datePiker弹出框被下面的div给遮挡住了,以前也碰到过这样类似的问题,之前直接在style中添加"z-index:1000".但是现在使用angular ...

  10. Linux下解决用户不能执行sudo的方法

    报错: xxx is not in the sudoers file.  This incident will be reported. Linux默认没有为当前用户开启sudo权限! $ su  $ ...