Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to use andThen in order to pattern match Futures?

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.

like image 979
Bob Dem Avatar asked May 18 '17 11:05

Bob Dem


People also ask

How does Scala Future work?

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.

How do you handle Future Scala?

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.

Why ++ is not allowed in pattern matching?

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] .

What Future sequence does?

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.


1 Answers

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.

like image 160
OlivierBlanvillain Avatar answered Sep 29 '22 03:09

OlivierBlanvillain