gpt4 book ai didi

带有类型注释的 for-comprehension 中的 scala 异常

转载 作者:行者123 更新时间:2023-12-04 11:51:09 25 4
gpt4 key购买 nike

我试图理解在 for-comprehension 中处理空值和类型注释时看起来很奇怪的行为。

举个例子:

def f(): String = null

for {
a <- Option("hello")
b = f()
} yield (a, b)

结果达到预期:
//> res0: Option[(String, String)] = Some((hello,null)) 

但是,如果我为 b 的类型添加类型注释
def f(): String = null

for {
a <- Option("hello")
b: String = f()
} yield (a, b)

然后我得到一个运行时异常:
//> scala.MatchError: (hello,null) (of class scala.Tuple2)

为什么会发生这种情况?不是 b隐式类型 String在第一个例子中呢?第二个示例中的显式类型注释有何变化?

(注意,示例是在 Scala 2.11.4 中运行的)

最佳答案

null不是任何东西的实例:

scala> (null: String) match { case _: String => }
scala.MatchError: null
... 33 elided

scala> val s: String = null
s: String = null

scala> s.isInstanceOf[String]
res1: Boolean = false

http://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#type-patterns

类型模式指定非空。

显示翻译的一个技巧是评论显示:
scala> for {
| a <- Option("hello")
| b: String = f()
| } yield (a, b) // show
object $read extends scala.AnyRef {
def <init>() = {
super.<init>;
()
};
object $iw extends scala.AnyRef {
def <init>() = {
super.<init>;
()
};
import $line4.$read.$iw.$iw.f;
object $iw extends scala.AnyRef {
def <init>() = {
super.<init>;
()
};
val res1 = Option("hello").map(((a) => {
val b: String = f;
scala.Tuple2(a, b)
})).map(((x$1) => x$1: @scala.unchecked match {
case scala.Tuple2((a @ _), (b @ (_: String))) => scala.Tuple2(a, b)
}))
}
}
}
scala.MatchError: (hello,null) (of class scala.Tuple2)
at $anonfun$2.apply(<console>:10)
at $anonfun$2.apply(<console>:10)
at scala.Option.map(Option.scala:145)
... 39 elided

关于带有类型注释的 for-comprehension 中的 scala 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27789412/

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