Scala Future的优雅处理[Either]]

时间:2015-10-23 19:04:43

标签: scala either

我有一个形状如下的类型:

val myType: Future[Either[MyError, TypeA]] = // some value

我知道我可以在此模式匹配并转到Right或Left类型,但问题是我必须嵌套我的模式匹配逻辑。我正在寻找更优雅的处理方式吗?有什么建议吗?

2 个答案:

答案 0 :(得分:5)

如果您将MyError编码为例外情况,则不再需要Either,只需针对完成情况进行模式匹配,或使用recoverWith将其映射到另一种类型:

myType.onComplete {
  case Success(t) =>
  case Failure(e) =>
}

要映射现有的Either类型,您可以执行以下操作:

case class MyException(e: MyError) extends Exception

def eitherToException[A](f: Future[Either[MyError,A]]): Future[A] = {
  f.flatMap {
    case Left(e) => Future.failed(MyException(e))
    case Right(x) => Future.successful(x)
  }
}

val myType2 = eitherToException(myType)

或者,如果MyErrorTypeA在您的控制之下,您可以创建一个常见的超类型和模式匹配:

sealed trait MyResult
final case class MyError() extends MyResult
final case class TypeA() extends MyResult

myType.map {
  case MyError() => ...
  case TypeA() => ...
}

答案 1 :(得分:1)

您可以创建自定义提取器对象:

object FullSuccess {
  def unapply[T](x: Try[Either[MyError, T]]) = x match {
    case Success(Right(x)) => Some(x)
    case _ => None
  }
}

object PartSuccess {
  def unapply[T](x: Try[Either[MyError, T]]) = x match {
    case Success(Left(err)) => Some(err)
    case _ => None
  }
}

并且

val myType: Future[Either[MyError, TypeA]] = // some value

myType.onComplete {
  case FullSuccess(x) => ... // equivalent to case Success(Right(x))
  case PartSuccess(x) => ... // equivalent to case Success(Left(x))
  case Failure(e) => ...
}