Why do I need to use andThen to match Futures?
I found out that to match Future
fur Success
/ pattern Failure
I need to use andThen
(or onComplete
, onSuccess
...) and cannot use map
, Why is this?
What I wanted to do (simplified, I agree for Success
, etc.):
val f1 = Future(throw new Exception("Oops"))
f1 map { case Failure(e) => ??? }
gives:
error: constructor cannot be instantiated to expected type;
found : scala.util.Failure[T]
required: Nothing
f1 map { case Failure(e) => ??? }
What I ended up with:
val f1 = Future(throw new Exception("Oops"))
f1 andThen { case Failure(e) => ??? }
I would like to understand why map
it cannot be used here.
source to share
The answer is in the signature map
: it takes A => B
and returns a Future[B]
. If you like, you can look Future
like this:
type Future[A] = Async[Either[Throwable, A]]
Future#map
, Future#flatMap
and Future.apply
treat this "stack" of types as one big thing with a hole ( Future
it's basically a special cased monad transformer). When you are map
/ flatMap
on Future
, you only work with the inner A
.
source to share