问题描述
Akka(或Scala 2.10中的标准库)中是否存在将 Future [A]
转换为的方法? 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)
}
这似乎是一个普通的任务,我想知道我是否忽略了某些东西。我对Scala 2.9 / Akka和Scala 2.10的答案感兴趣。
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.
推荐答案
缺少此方法的主要原因是:它确实没有很好的语义:静态类型 Future [Either [Throwable,T]]
不能确保将来不会失败,因此类型更改不会使您受益
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
}
}
它与Akka 2.0期货非常相似,因此我将练习留给读者。
It works very similarly with Akka 2.0 futures, hence I leave that exercise to the reader.
这篇关于将Akka的Future [A]转换为Future [Either [Exception,A]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!