我试图理解在 for-comprehension 中处理 null 和类型注释时看起来很奇怪的行为。
举个例子:
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 中运行)