如何从未来左右

时间:2015-12-22 17:05:08

标签: scala

我的功能如下:

Complex

正如您所看到的,如果Future失败,那么它将触发恢复体内的部分函数。这将返回Left并满足Either类型的左侧部分。我坚持的是如果Goo未来成功完成,如何返回Right。

我尝试了以下内容:

def bar(x : Int) : Either[String, Future[Option[Foo]]] = {
  Goo() recover { case e => Left("Some error string") }
}

但是,我收到类型错误,指出def bar(x : Int) : Either[String, Future[Option[Foo]]] = { Goo().map(x => Right(Future.successful(x))) recover { case e => Left("Some error string") } } 的返回类型为bar

如何返回Future[Either[String, Future[Foo]]] Right(x) x类型的某些值?

更新

Foo

1 个答案:

答案 0 :(得分:0)

您没有定义Goo,但我现在假设以下内容:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

case class Foo(n: Int)

/** Takes a string and returns a future int-parsing of it */
def Goo(s: String): Future[Foo] = Future {
  Foo(java.lang.Integer.parseInt(s))  // will throw an exception on non-int
}

然后,如果您希望bar(s: String)返回Either[String, Option[Foo]] OptionSome[Foo],如果该号码可解析且为正,或None如果可解析但非正面,String解释了为什么它无法解析,你可以这样做:

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.control.NonFatal

def bar(s: String): Future[Either[String, Option[Foo]]] = {
  Goo(s).map { foo: Foo =>
    Right(if (foo.n > 0) Some(foo) else None)
  }.recover {
    case NonFatal(e) => Left("Failed to parse %s: %s".format(s, e))
  }
}

瞧:

scala> Await.result(bar("4"), Duration.Inf)
res1: Either[String,Option[Foo]] = Right(Some(Foo(4)))

scala> Await.result(bar("-4"), Duration.Inf)
res2: Either[String,Option[Foo]] = Right(None)

scala> Await.result(bar("four"), Duration.Inf)
res3: Either[String,Option[Foo]] = Left(Failed to parse four: java.lang.NumberFormatException: For input string: "four")
相关问题