英文:
Scala for-comprehension and Option
问题
这段代码引发了一个异常:
example.scala:14: error: ambiguous reference to overloaded definition,
both method * in class Int of type (x: Char): Int
and method * in class Int of type (x: Byte): Int
match argument types (Nothing)
(x, y, z, x + y + z, x * y * z)
如果我们使用 val y = Option.empty[Int] 而不是 val y = None,那么在某种意义上它会工作,result1 包含了 None。
但是为什么会对 * 函数有限制呢?无论如何,我们都不会得到 (2, None, 5, None, None)。我假设如果一个值是 None,那么这一步会被跳过,那么为什么 * 必须明确引用一个定义呢?
英文:
object main {
def main(args: Array[String]) = {
val x = Option(2)
val y = None // works with: Option.empty[Int]
val z = Option(5)
val result1 = for {
x <- x
y <- y
z <- z
} yield {
(x, y, z, x + y + z, x * y * z)
}
println(result1)
}
}
This code yields an exception:
example.scala:14: error: ambiguous reference to overloaded definition,
both method * in class Int of type (x: Char): Int
and method * in class Int of type (x: Byte): Int
match argument types (Nothing)
(x, y, z, x + y + z, x * y * z)
If we use val y = Option.empty[Int] instead of val y = None, it works in the sense that result1 contains None.
But why are there any restrictions on the function * ? We don't get (2, None, 5, None, None) anyway. I assumed the step would be skipped if one value was None, so why must * unambiguously refer to a definition?
答案1
得分: 4
代码部分不翻译,只返回翻译好的内容:
错误发生是因为 y 的类型为 None,它扩展了 Option[Nothing]。
在 for 推导式中,内部的 y 因此具有 Nothing 类型,您不能将 * 应用于 Nothing。
如果您显式将(外部)y 类型为 Option[Int],错误将消失:
val y: Option[Int] = None
当您说:
> 假设如果一个值是 None,那么步骤会被跳过
这在 运行时 是正确的,但在编译时,编译器只看到了 Option[Int] 和 Option[Nothing] 的组合。
英文:
The error happens because y has type None which extends Option[Nothing].
In the for comprehension, the inner y thus has a Nothing type and you cannot apply * to Nothing.
The error goes away if you explicitly type (outer) y to Option[Int]:
val y: Option[Int] = None
When you say:
> assumed the step would be skipped if one value was None
This is true at runtime, but at compile time the compiler only sees a combination of Option[Int] and Option[Nothing].
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论