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

前端之家收集整理的这篇文章主要介绍了Scala:在使用空值取消应用元组时出现奇怪的MatchError前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
任何精通 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背后的推理.

猜你在找的Scala相关文章