map(), flatMap() on Futures & Options in scala

Reading Time: 5 minutes

In this blog, we would be looking at how map() and flatMap() operations work with Option and Future of scala, literally speaking both Futures and Options are very effective features of scala, A Future lets us have a value from some task on a differnt thread and Option provides us a hand from null of java as using null in scala is seen a very bad approach in functional programming.

In my previous blog, map and flatMap in Scala for collections we had a quite basic but yet effective understanding how map() and flatMap() works with collections in scala, keeping  in contrast  with my last blog, one may find it pretty weird like the methods that works on collections can also work on Futures and Options too, but we will look how these methods put us at ease while handling Futures[+T] and Options[+A]. Now let’ s first look the above operations help us dealing with Option[A+], So let’s get started with moving toward Options.

map() and flatMap on Option[+A]

So if we look at the signatures of map() and flatMap() methods in class Option they look like this:

both the methods above are final keeping that aside we see that signatures of  both the methods looks pretty much same like signature of map() and flatMap() in class List, for instance like for a list map operation take lambda that takes a parameter of type A and returns an element of type B and in flatMap takes a parameter of type A and return a parameter of type of List[B] similarly map and flatMap are same for options, so let’s look at something more interesting with the help of some code,

map() on Option[+A]

We know map() is a transformer method, on Option it works just like that

the code generated by scala REPL clearly displays that how the transformations are performed by map on an option value.

flatMap() on Option[+A]

now let’s move towards the interesting part flatMap(), what it is supposed to do in case of Option so the flatMap() gives us the liberty to return the type of value that we want to return after the transformation, unlike map() in wherein when a parameter has the value Some the value would be of type Some what so ever, but its not with the case with flatMap()

the code snippet above clearly shows it, so is that it ? No not yet lets look on to one more feature of flatMap() on Option[+A]that comes to be real handy when we need to extract value out of options, supposedly we have list of type List[Option[Int]] now I am only interested in values that have some value which seems to be an obvious usecase in most of the times, we can simply do it using a ​flatMap() operation

see how efficiently flatMap has done it for us, we can also do the same thing using method flatten, similarly we can also use flatMap operation wherever we flatten nested Options wrappers to flatten the structure as per our needs.

I hope I was able to clear it out how these operations work for Option[+A]

map() and flatMap on Future[+A]

map() on Future[+A]

Now let’s leap forward towards Future[+A], now just like we discussed above and in my last blog as well, that map() operation is a transformer, hence we can predict it that on futures it would work like that only so if we apply map on a future, the variable inside the body of map would be the type of variable that was wrapped on the future and hence we can easily do the desired operation on that and after that the map would return the transformed value wrapped in future, it would be more clear from the code below

the above code generated by scala REPL clearly show how map() transformer gives us the type of value in its body unwrapped in future like we used + on ​ y which is an Int

flatMap() on Future[+A]

Now let’s see how flatMap() works for Future, but before that let’s look at the signatures of map and flatMap in scala in class Future

we can see the signature is similar to what we have in case of Options or Collections in ​map() it takes a lambda that takes T and returns S, and for flatMap() that lambda is that takes T and returns Future[S]we can also see that both the method takes an ExecutionContextimplicitly, which is out of the scope for our discussion today so whenever you need to execute any code in scala REPL of IDE, add these two import statements

now since the flatMap() signature depicts that it returns the value wrapping it in Future, the awesome thing about the flatMap() operation is that it not just only transforms  the value for the Future but also lets us to explicitly wrap the value to form the result as either Future.successful and Future.failed  depending upon our usecase, as this could be required when we want to fail our Future explicitly depending upon the value that we got from the future on which we have applied flatMap() operation let’s understand it with a code snippet

so the method getTable(num: Int): Future[List[Int]] returns the List of table of the number provided to it if it is not zero, if zero it would simply return a completed Future containing an empty List so we are putting a call to flatMap and checking if we got the Empty list we are throwing the exception and failing our Futureexplicitly.

Some points more I would like to add, map and flatMap are just the transformers on a Future they should not be mistaken as callbacks like onComplete, onFailure, onSuccess , a map() or a flatMap() are non – blocking and would proceed further if the target Future is not completed, for more you may look into my github repo map and flatmap on Future and Option, so that’s all for this time I hope I was able to make things clear, suggestions are always welcomed and you can also drop your comments below  keep coding and happy coding. 🙂


Written by 

Shubham Verma is a software consultant. He likes to explore new technologies and trends in the IT world. Shubham is familiar with programming languages such as Java, Scala, C, C++, HTML, Javascript and he is currently working on reactive technologies like Scala, Akka , spark and Kafka. His hobbies includes playing computer games and watching hollywood movies.

1 thought on “map(), flatMap() on Futures & Options in scala7 min read

Comments are closed.