Why do these similar statements call objects of different types?

In Scala for the Intolerant, the author provides the following two examples for โ€œunderstandingโ€:

for (c <- "Hello"; i <- 0 to 1) yield (c + i).toChar // Yields "HIeflmlmop" for (i <- 0 to 1; c <- "Hello") yield (c + i).toChar // Yields Vector('H', 'e', 'l', 'l', 'o', 'I', 'f', 'm', 'm', 'p') 

However, he did not mention why the output is a string in the first case, and Vector in the second. Can anyone explain this? Thanks.

+6
source share
1 answer

Your first example translates into something like:

 "Hello".flatMap(c => (0 to 1).map(i => (c + i).toChar)) 

and second -

 (0 to 1).flatMap(i => "Hello".map(c => (c + i).toChar)) 

StringOps.flatMap returns String , so your first example also returns String . Range.flatMap instead returns IndexedSeq .

+10
source

All Articles