Bob*_*Dem 4 scala future pattern-matching
我发现为了模式匹配Futurefur Success/ Failure,我需要使用andThen(或onComplete,onSuccess...)而不能使用map.这是为什么?
我想做什么(简化,我匹配Success等等):
val f1 = Future(throw new Exception("Oops"))
f1 map { case Failure(e) => ??? }
Run Code Online (Sandbox Code Playgroud)
得到:
error: constructor cannot be instantiated to expected type;
found : scala.util.Failure[T]
required: Nothing
f1 map { case Failure(e) => ??? }
Run Code Online (Sandbox Code Playgroud)
我最终做了什么:
val f1 = Future(throw new Exception("Oops"))
f1 andThen { case Failure(e) => ??? }
Run Code Online (Sandbox Code Playgroud)
我想明白为什么map不能在这里使用.
答案是签名map:它需要一个A => B并返回一个Future[B].如果愿意,你可以看一下Future如下:
type Future[A] = Async[Either[Throwable, A]]
Run Code Online (Sandbox Code Playgroud)
Future#map,Future#flatMap并将Future.apply这种类型的"堆栈"视为一个带孔的大事(Future基本上是一个特殊的套管monad变压器).当你map/ flatMap上Future,你只是在内部运作A.