任何精通
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背后的推理.