Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do these similar looking statements yield objects of different types?

Tags:

scala

In the book 'Scala for the Impatient' the author provides the following two examples for 'for-comprehension':

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 didn't mention why the output is a String in the first case, and Vector in the second. Could someone please explain? Thanks.

like image 313
Pankaj Godbole Avatar asked Apr 08 '14 11:04

Pankaj Godbole


1 Answers

Your first example is translated into something like:

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

and the second to

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

StringOps.flatMap returns a String, so your first example returns a String as well. Range.flatMap returns an IndexedSeq instead.

like image 63
Lee Avatar answered Oct 06 '22 15:10

Lee