为什么我需要使用andThen才能模拟匹配期货?

时间:2017-05-18 11:33:17

标签: scala pattern-matching future

我发现为了模式匹配Future fur Success / Failure,我需要使用andThen(或onComplete,{{1 }}})并且不能使用onSuccess。那是为什么?

我想做什么(简化,我匹配map等等):

Success

给出:

val f1 = Future(throw new Exception("Oops"))
f1 map { case Failure(e) => ??? }

我最终做了什么:

error: constructor cannot be instantiated to expected type;
 found   : scala.util.Failure[T]
 required: Nothing
       f1 map { case Failure(e) => ??? }

我想了解为什么val f1 = Future(throw new Exception("Oops")) f1 andThen { case Failure(e) => ??? } 不能在这里使用。

2 个答案:

答案 0 :(得分:5)

答案在map的签名中:它需要A => B并返回Future[B]。如果愿意,您可以按如下方式查看Future

type Future[A] = Async[Either[Throwable, A]]

Future#mapFuture#flatMapFuture.apply将这种类型的“堆栈”视为带洞的单个大事(Future基本上是一个特殊的套装monad变换器)。当您map上的flatMap / Future时,您只能在内部A上操作。

答案 1 :(得分:2)

因为类型签名不正确。如果您想要映射Future[A],则需要提供一个A并生成B的函数,这不是您正在做的事情。你要找的是recover

f1 recover { case e => // e is already a `Throwable` here ??? }