gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:37:47 24 4
gpt4 key购买 nike

任何精通 Scala 的人都可以解释为什么这样做:

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

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

但不是这个?
scala> Tuple2[String,String]("w3wre", null)
res1: (String, String) = (w3wre,null)

scala> val (s1:Any, s2:Any) = Tuple2[String,String]("w3wre", null)
scala.MatchError: (w3wre,null) (of class scala.Tuple2)
at .<init>(<console>:9)
at .<clinit>(<console>)
...

(显然 Any-type 可以包含 null s:
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:取消应用带有空值的元组时出现奇怪的MatchError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31474349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com