加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala:在使用空值取消应用元组时出现奇怪的MatchError

发布时间:2020-12-16 18:02:01 所属栏目:安全 来源:网络整理
导读:任何精通 Scala的人都可以解释为什么这样有效: scala Tuple2[String,String]("w3wre","werffd")res0: (String,String) = (w3wre,werffd)scala val (s1:Any,s2:Any) = Tuple2[String,"werffd")s1: Any = w3wres2: Any = werffd 但不是吗? scala Tuple2[Stri
任何精通 Scala的人都可以解释为什么这样有效:

scala> Tuple2[String,String]("w3wre","werffd")
res0: (String,String) = (w3wre,werffd)

scala> val (s1:Any,s2:Any) = Tuple2[String,"werffd")
s1: Any = w3wre
s2: Any = werffd

但不是吗?

scala> Tuple2[String,null)
res1: (String,null)

scala> val (s1:Any,null)
scala.MatchError: (w3wre,null) (of class scala.Tuple2)
    at .<init>(<console>:9)
    at .<clinit>(<console>)
...

(显然Any-type可以包含空值:

scala> val n:Any = null
n: Any = null

scala> val n:Any = null.asInstanceOf[String]
n: Any = null

)

解决方法

语言规范明确指出这种类型模式不匹配null( 8.2 Type Patterns,强调我的):

Type patterns consist of types,type variables,and wildcards. A type pattern T is of one of the following forms:

  • A reference to a class C,p.C,or T#C. This type pattern matches any non-null instance of the given class.

但是,我不知道语言设计者在不匹配null背后的推理.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读