我发现为了模式匹配 Future
皮草 Success
/Failure
, 我需要使用 andThen
(或 onComplete
, 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) => ??? }
我想了解为什么
map
不能在这里使用。
最佳答案
答案在 map
的签名中: 它需要一个 A => B
并返回 Future[B]
.如果愿意,您可以查看 Future
如下:
type Future[A] = Async[Either[Throwable, A]]
Future#map
, Future#flatMap
和 Future.apply
将这种类型的“堆栈”视为一个带有孔的大东西(Future
基本上是一个特殊的单子(monad)变压器)。当你map
/flatMap
在 Future
,您只对内部 A
进行操作.
关于scala - 为什么我需要使用 andThen 来匹配 Futures?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046609/