scala - 为什么我需要使用 andThen 来匹配 Futures?

标签 scala pattern-matching future

我发现为了模式匹配 Future皮草 Success/Failure , 我需要使用 andThen (或 onCompleteonSuccess ...)并且不能使用 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) => ??? }

我想了解为什么map不能在这里使用。

最佳答案

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

type Future[A] = Async[Either[Throwable, A]]
Future#map , Future#flatMapFuture.apply将这种类型的“堆栈”视为一个带有孔的大东西(Future 基本上是一个特殊的单子(monad)变压器)。当你map/flatMapFuture ,您只对内部 A 进行操作.

关于scala - 为什么我需要使用 andThen 来匹配 Futures?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046609/

相关文章:

list - 如何获取在 Scala 的列表中多次出现的所有元素的集合?

java - 如何在 Java 中使用带有 WebClient 的 Vertx 路由器中的 future

php - 选择字符串的一部分

swift Steam : catchMap not being awaited

http - super 0.12.x : Implementing Service for a struct

scala boolean 变量需要动态改变

regex - 使用正则表达式从键中的映射访问值

scala - Clojure 中的 mapcat 和 Scala 中的 flatMap 在操作方面有什么区别?

java - 正则表达式内部数字检查

scala - 寻找在 Scala 中进行模式匹配时如何使用 "@_*"的示例