Scala的for-comprehension和Option。

huangapple go评论50阅读模式
英文:

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].

huangapple
  • 本文由 发表于 2023年6月15日 23:51:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定