Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

scala - converting Akka's Future[A] to Future[Either[Exception,A]]

Is there a method in Akka (or in the standard library in Scala 2.10) to convert a Future[A] which might fail into a Future[Either[Exception,A]]? I know that you can write

f.map(Right(_)).recover {
  case e:Exception => Left(e)
}

It just seems to be such a common task that I wonder whether I have overlooked something. I'm interested in answers for Scala 2.9/Akka and Scala 2.10.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The primary reason why this method is missing is that it does not really have good semantics: the static type Future[Either[Throwable, T]] does not ensure that that future cannot fail, hence the type change does not gain you much in general.

It can of course make sense if you control all the code which handles those futures, and in that case it is trivial to add it yourself (the name is due to me posting before first coffee, feel free to replace with something better):

implicit class FutureOps[T](val f: Future[T]) extends AnyVal {
  def lift(implicit ec: ExecutionContext): Future[Either[Throwable,T]] = {
    val p = promise[Either[Throwable,T]]()
    f.onComplete {
      case Success(s)  => p success Right(s)
      case Failure(ex) => p success Left(ex)
    }
    p.future
  }
}

It works very similarly with Akka 2.0 futures, hence I leave that exercise to the reader.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...