Say I have following code:
object ForComprehension {
def generateSomeSeq(n: Int): List[Int] = (1 to n).toList
def square(n: Int): List[Int] =
for (x <- generateSomeSeq(n)) yield x * x
}
It all works fine. But for some reason I modify the result of first method to Set instead of List:
object ForComprehension {
def generateSomeSeq(n: Int): Set[Int] = (1 to n).toSet
def square(n: Int): List[Int] =
for (x <- generateSomeSeq(n)) yield x * x
}
The scala compiler complains there’s a type mismatch in first generator of for comprehension. Although it makes sense, I still expect it works in both cases. After all, there’s no visual clue in for comprehension that it expects a List instead of a Set. I need to read both signatures to diagnose the type mismatch error.
Or I shouldn’t expect such syntactical locality for for comprehension in the first place, should I?
The for comprehension in your example is really just syntactic sugar for a call to
mapand the return type ofmapis indeed determined by the type it is called on. More precisely, it is determined by the implicitCanBuildFromthat is available. So to make your code compile, you can convert the for comprehension to a map call and explicitly pass the usually implicit parameter:About how
breakOutworks, see this question.