3 ms·
My favorite syntax sugar in Scala. Especially in future composition. Is there a good theoretical (not technical) reason why we can't mix types in a for-yield s
by eranation 12y ago
My favorite syntax sugar in Scala. Especially in future composition.
Is there a good theoretical (not technical) reason why we can't mix types in a for-yield structure? There is an implicit conversion from Option to Seq added, so I can mix lists and options, but is there a fundamental issue preventing mixing other types? e.g. in the basic math of it?
- runT1ME 12y agoAll 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.