当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: