Scala的元组是正确的

时间:2014-06-05 17:27:46

标签: scala for-comprehension

假设我有以下代码:

val either: Either[String, (Int, Int)] = Right((1,2))
for {
  (a, b) <- either.right
} yield a + b

当我在REPL中评估它时,我得到了

  

:13:错误:构造函数无法实例化为预期   类型;发现:(T1,T2)要求:   scala.util.Either [Nothing,(Double,Double)]                 (a,b)&lt; - a.right                 ^:14:错误:未找到:值a                 屈服a + b                         ^

为什么会出现这样的错误?我不能模仿Either的元组中的元组匹配吗?

1 个答案:

答案 0 :(得分:5)

问题似乎是一个scala bug https://issues.scala-lang.org/browse/SI-7222。将for comprehension转换为flatMap / map符号似乎有效。

val either: Either[String, (Int, Int)] = Right((1, 2))
either.right.map {
  case (a, b) =>
    a + b
}

either: Either[String,(Int, Int)] = Right((1,2))
res0: Serializable with Product with scala.util.Either[String,Int] = Right(3)