Scala的元组是正确的

mak*_*aks 6 scala for-comprehension

假设我有以下代码:

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

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

:13:错误:构造函数无法实例化为期望的类型; 发现:(T1,T2)必需:scala.util.Either [Nothing,(Double,Double)](a,b)< - a.right ^:14:错误:未找到:值a}产生a + b ^

为什么我有这样的错误?我不能模仿来自Either's right的元组匹配吗?

fer*_*k86 6

问题似乎是一个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)
Run Code Online (Sandbox Code Playgroud)