How to compose Future and Option in Scala
Update (June 24, 2016) : New example using Hamsters lib
In Scala, it’s easy to compose options :
Note : you can read my helper about for comprehension translation to map/flatMap
.
It’s also easy to compose futures, in a non blocking way :
But is it easy to compose several Future[Option[A]]? It’s a common problem if you call sequentially several external resources, that can give you one or zero value.
We can’t compose easily fob
and foa
: types will mismatch because futures and options don’t compose naturally.
Fortunately, there are some solutions.
Handmade binding
You can solve this with pattern matching :
(*) : In the for, call fob with the value inside the option and get a Future[Option[String]].
Doing this, you can compose result from foa
and fob
and keep consistent types.
Using a custom FutureO monad
This is an idea from Edofic’s blog. It allows more natural composition of Option and Future types.
You can create a custom FutureO
monad that will compose well with other FutureO
instances.
You just need to define a constructor and flatMap
(plus map
as it’s used by for comprehension syntactic sugar) :
Then you can use a simple for comprehension form :
Or, with flatMap
:
Using a Scalaz monad transformer
Finally, if you want to generalize this kind of usage, you should try Scalaz monad transformers, which work for a larger kind of types than options and futures.
Update : Using Hamsters monad transformers
Since the moment I wrote this post, I’ve made a small library that provides (among other things) some simple monad transformers :
You can find more information about Hamsters here.