Kannan
Kannan

Reputation: 307

Output in Yield statement is different

for (c <- "Hello"; i <- 0 to 1) yield (c + i).toChar

why the above line yield is different from the below line yield

for (i <- 0 to 1; c <- "Hello") yield (c + i).toChar

Even though (c + i).toChar is same for the above lines and the output should be the same but it is different.

Upvotes: 1

Views: 45

Answers (1)

jwvh
jwvh

Reputation: 51271

The demonstrates that the order of generators is significant. (Every <- is a "generator".)

The 1st generator is "slower" in that it advances only after the 2nd generator completes a cycle.

The 1st generator also guides the output collection type. If it iterates through a String then the output is a String, if the output elements are still Chars. If it iterates through a Range then the output is an IndexedSeq[]. (According to the Scala docs, Range is "a special case of an indexed sequence.")

Upvotes: 3

Related Questions