I have this issue that I have to work around every time. I can’t map over something that is contained within a Future using a for comprehension.
Example:
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
val f = Future( List("A", "B", "C") )
for {
list <- f
e <- list
} yield (e -> 1)
This gives me the error:
error: type mismatch;
found : List[(String, Int)]
required: scala.concurrent.Future[?]
e <- list
^
But if I do this it works fine:
f.map( _.map( (_ -> 1) ) )
Should i not be able to do this by using a for comprehension, is the reason it works in my other example that I do not flatmap? I’m using Scala 2.10.0.
Well, when you have multiple generators in a single for comprehension, you are flattening the resulting type. That is, instead of getting a
List[List[T]], you get aList[T]:Now, how would you flatten a
Future[List[T]]? It can’t be aFuture[T], because you’ll be getting multipleT, and aFuture(as opposed to aList) can only store one of them. The same problem happens withOption, by the way:The easiest way around it is to simply nest multiple for comprehensions:
In retrospect, this limitation should have been pretty obvious. The problem is that pretty much all examples use collections, and all collections are just
GenTraversableOnce, so they can be mixed freely. Add to that, theCanBuildFrommechanism for which Scala has been much criticized makes it possible to mix in arbitrary collections and get specific types back, instead ofGenTraversableOnce.And, to make things even more blurry,
Optioncan be converted into anIterable, which makes it possible to combine options with collections as long as the option doesn’t come first.But the main source of confusion, in my opinion, is that no one ever mentions this limitation when teaching for comprehensions.