I found out that in order to pattern match Future
fur Success
/Failure
, I need to use andThen
(or onComplete
, onSuccess
...) and cannot use map
. Why is that?
What I wanted to do (simplified, I am matching for Success
and so on as well):
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 doing:
val f1 = Future(throw new Exception("Oops"))
f1 andThen { case Failure(e) => ??? }
I would like to understand why map
cannot be used here.
Future represents a result of an asynchronous computation that may or may not be available yet. When we create a new Future, Scala spawns a new thread and executes its code. Once the execution is finished, the result of the computation (value or exception) will be assigned to the Future.
Handle the result of a future with methods like onComplete , or combinator methods like map , flatMap , filter , andThen , etc. The value in a Future is always an instance of one of the Try types: Success or Failure.
You can only pattern-match on data constructors, and ++ is a function, not a data constructor. Data constructors are persistent; a value like 'c':[] cannot be simplified further, because it is a fundamental value of type [Char] .
This Future. sequence() function converts a list of Futures into a single Future that means collections of Futures into a single Future. In simple words, List[Future[T]] ======> Future[List[T]] . It is also known as composing Futures.
The answer is in the signature of map
: it takes a A => B
and returns a Future[B]
. If you will, you can look at a Future
as follows:
type Future[A] = Async[Either[Throwable, A]]
Future#map
, Future#flatMap
and Future.apply
view this "stack" of types as a single big thing with a hole (Future
is basically a special cased monad transformer). When you map
/flatMap
on a Future
, you are only operating on the inner A
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With