Scala:匹配左侧并返回左侧,而不展开对象
我有一个用例,我想返回一个左撇子的未来。当我将其展开并再次创建时:Scala:匹配左侧并返回左侧,而不展开对象,scala,Scala,我有一个用例,我想返回一个左撇子的未来。当我将其展开并再次创建时: fooEither match { case Right(value) => //.. Some logic. returns Future(Right(MyObj)) case Left(value) => Future(Left(value)) } 在第二种情况下,我想再次摆脱对象创建。 比如: fooEither match { case Right(value) => //..
fooEither match {
case Right(value) => //.. Some logic. returns Future(Right(MyObj))
case Left(value) => Future(Left(value))
}
在第二种情况下,我想再次摆脱对象创建。
比如:
fooEither match {
case Right(value) => //.. Some logic. returns Future(Right(MyObj))
case left: Left(_) => Future(left)
}
它给了我一个类型不匹配的编译错误。问题是
Left
携带了超级类型的两个类型参数:
trait Foo; trait Bar; trait Quux
import scala.concurrent.Future
def test(e: Either[Foo, Bar]): Future[Either[Foo, Quux]] = e match {
case Right(bar) => Future.successful(Right(new Quux {}))
case left: Left[Foo, Bar] => Future.successful(left) // XXX
}
这不会编译,因为在//XXX
中,您试图返回未来[Foo,Bar]]
。然而,以下工作:
def test(e: Either[Foo, Bar]): Future[Either[Foo, Quux]] = e match {
case Right(bar) => Future.successful(Right(new Quux {}))
case left: Left[Foo, Nothing] => Future.successful(left)
}
尽管编译器发出警告:
这是“安全的”,因为您永远无法从Left
获取第二个类型参数的元素,但它是“脏的”,就像您要将您的Left转换为Left[Foo,qux]
。我建议重新构造左侧
,然后通过推理得到正确的类型。我宁愿使用它,而不是复制或类型的完整类型参数,如下所示:
case left @ Left(_) => Future.successful(left)
另请参见:这也有相同的问题,您在此处绑定的左侧
的B
类型错误。您必须对其进行强制转换或重建Left
。抱歉,问题并没有说明/Left/Right的A、B类型。我以为他们是一样的。
case left @ Left(_) => Future.successful(left)