如果我用 Option 的值定义创建一个 for 理解,它会按预期工作:
scala> for (a <- Some(4); b <- Some(5); val p = a * b) yield p
res0: Option[Int] = Some(20)
如果我没有值定义,则使用 Either 做同样的事情:
scala> for (a <- Right(4).right; b <- Right(5).right) yield a * b
res1: Either[Nothing,Int] = Right(20)
但是,如果我使用值定义,scala 似乎会为 for 理解推断错误的容器类型:
scala> for (a <- Right(4).right; b <- Right(5).right; val p = a * b) yield p
<console>:8: error: value map is not a member of Product with Serializable with Either[Nothing,(Int, Int)]
for (a <- Right(4).right; b <- Right(5).right; val p = a * b) yield p
^
为什么这样做?有什么方法可以绕过这种行为?