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.
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
.
Because the type signature is wrong. If you want to display the map above Future[A]
you need to provide a function with A
and create B
, which is not how you seem to be doing. You are looking for recover
:
f1 recover { case e => // e is already a `Throwable` here ??? }
Future[A].map
gets a function from A => B
(B is any type)
if you want to combine try simple
myFuture match {
case Success(x) =>
case Failure(e) =>
}