3 ms·
All for comprehension is syntactic sugar for repeated calls to flatMap. So for { a <- someOption b <- someOtherOPtion } yield a + b //r
by runT1ME 12y ago
All for comprehension is syntactic sugar for repeated calls to flatMap.
So
for {
a <- someOption
b <- someOtherOPtion
} yield a + b //returns Option[Int]
ends up being
someOption.flatMap(a => someOtherOption.map(b => a+b) )
and remember, all flatMap does is 'map', (so you'd get Option[Option[Int]), then "flatten" it so you end up with just Option[Int]. So if you have 4 'nestings', you only get one level of Option and not 4.
The signature for all flatMaps is ...
class Something[A] {
def flatMap[B](f: A => Something[B]): Something[B]
}
So, you could have that for Option, for Future, for NonEmptyList, Stream, etc.
But they can't mix and match cause you don't necessarily know how to 'flatten' a List into a future. List[Future[A]] is something very different than say just a List[A]. (One is a concurrent computation).
So, yes, you can do implicit conversions to alleviate this, or you can do what is known as a 'monad transformer' which sounds SUPER scary but I go over them in some slides and they're really easy to use.
https://speakerdeck.com/vmarquez/using-scala-futures-the-functional-way https://speakerdeck.com/vmarquez/using-scala-futures-the-fun...
If you want to get into the nitty gritty of how flatMap works and how to mix up futures/options.