scala中sealed关键字使用指南

                       

1. 防止继承滥用

​sealed关键字可以修饰类和特质(特质)密封类提供了一种约束:不能在类定义的文件之外定义任何新的子类。然而,这样做有什么用呢?

在scala源码中List的实现用到了sealed关键字。

抽象类List有sealed关键字修饰,接下来Nil和::分别继承了该List抽象类。那我们来尝试实现基于List实现一个自己的List:

scala> class NewList extends List<console>:7: error: illegal inheritance from sealed class List       class NewList extends List
  
  
  • 1
  • 2
  • 3

编译出错了,我们是不能在外部文件继承List类。所以,如果子类都明确的情况下,为了防止继承滥用,为抽象类添加sealed


2. 模式匹配

模式匹配是scala非常好用的一个语法特性。但是,如果当条件经常改变,我们可能会忘了修改相应的case,那么这种情况就可能会出现错误。看下边例子:

scala> :pas// Entering paste mode (ctrl-D to finish)  abstract class People  case object American extends People  case object Japanese extends People  case object Chinese extends People  case object Russia extends People  def people(p: People) = p match {    case American ⇒ println("American person")    case Japanese ⇒ println("Japanese person")    case Chinese ⇒ println("Chinese person")  }// Exiting paste mode, now interpreting.defined class Peopledefined object Americandefined object Japanesedefined object Chinesedefined object Russiapeople: (p: People)Unitscala> people(American)American personscala> people(Russia)scala.MatchError: Russia (of class Russia$)  at .people(<console>:13)  ... 33 elided
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

这时我们为People加上sealed,当我们编译代码时得到了一个警告:

<console>:18: warning: match may not be exhaustive.It would fail on the following input: Russia         def people(p: People) = p match {
  
  
  • 1
  • 2
  • 3

多温馨的一个提示啊。事情都不是绝对的,如果确定people只处理美国日本,中国人,编译时总是给这么个警告也挺闹心。能破吗?可定能,看代码:

  def people(p: People) = (p: @unchecked) match {    case American ⇒ println("American person")    case Japanese ⇒ println("Japanese person")    case Chinese ⇒ println("Chinese person")  }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3. sealed总结

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

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

【完】

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值