Scala FlatMap返回向量而不是String

时间:2017-08-22 17:56:46

标签: string scala flatmap

我正在关注马丁奥德斯基课程。并且有一个例子,他将flatMap应用于String并获得一个字符串作为回报,但我得到一个Vector。这是我正在使用的代码

val str = "Hello"
println(str flatMap (x => List("." , x)))

output: Vector(., H, ., e, ., l, ., l, ., o)
outputExpected: .H.e.l.l.o.w

enter image description here

2 个答案:

答案 0 :(得分:2)

"."String'.'Char

List('.', x)List[Char](如果xChar),可以展平为String

List(".", x)List[Any](如果x不是String),无法展平为String

答案 1 :(得分:1)

字符串是字符的集合,而不是字符串的集合。因此,当您使用flatMap创建字符集合时,它会选择String作为集合类型,但是当您创建字符串集合时,它不能使用{ {1}},因此必须使用String