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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With