I've explained this very recently -- hopefully someone can find the link. It's a recurring question, so it may well be closed.
At any rate, the outer generator controls the representation. That happens on each level, so if I have this:
for {
a <- A
b <- B
c <- C
} yield f(a, b, c)
Then the representation of f(a, b, c)
is controlled by C
, the representation of that is controlled by B
, and the representation of the final result is controlled by A
. So, for most practical purposes, the representation of the for comprehension is controlled by the first generator.
So what do I mean by "representation"? Well, a for comprehension is a monadic comprehension, usually (actually, it's just a set of calls to methods like flatMap
and map
, so it can be anything that typechecks). That means that given a monad M[A]
and a function A => M[B]
, then you can transform M[A]
in M[B]
, where M
, the monad, is the "representation".
This means that, for the most part, it would be impossible to combine Option
and List
in a for comprehension. All the collections have a common parent in GenTraversableOnce
, so there's no problem in combining them (though things are much more complicated than that under the hood).
However, there is an implicit conversion from Option
to Iterable
. That being the case, when Scala finds b <- a
in the first example, and knowing it can't pass an Option
because the comprehension is being "controlled" by a List
, it converts the Option
into an Iterable
, and everything works.
However, that doesn't happen in the second case. Doing a for comprehension with an Option
is ok, so there's no need to convert it into an Iterable
. Unfortunately, one cannot convert a List
into an Option
(what would be the result of such a conversion?), which results in the error.
Scala will not "backtrack" to a <- Some(List(1, 2))
and apply an implicit conversion to it, as type inference in Scala only goes forward -- what it decided before will remain as is.
I heartily recommend you look at the related questions and understand how a for comprehension is translated.