0

I am following martin odesky course. And there is example where he applies flatMap to String and gets a string in return but I am getting a Vector. Here is the code that I am using

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

pannu
  • 518
  • 7
  • 20

2 Answers2

2

"." is a String while '.' is a Char.

List('.', x) is a List[Char] (if x is a Char) which can be flattened to a String.

List(".", x) is a List[Any] (if x is not a String) which cannot be flattened to a String.


UPDATE -- This behavior has changed as of Scala 2.13.0.

"abc".flatMap(c => List('.', c))
//Scala 2.12.x returns String
//Scala 2.13.x returns IndexedSeq[Char] (REPL interprets as Vector)

This might be to insure a more consistent translation:

"abc".map(c => List('.', c)).flatten
//always returns IndexedSeq[Char]
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • that's great insight answer, scala is fun only if you know – pannu Aug 22 '17 at 18:08
  • `"."` is a `String` while `'.'` is a `Char` == true, but no matter which option I use, I get a `Vector` as a result (with Scala 2.13.6) – mpro Sep 09 '21 at 12:21
1

A string is a collection of characters, not a collection of strings. So when you use flatMap to create a collection of characters, it'll choose String as the type of collection, but when you create a collection of strings, it can't use String, so it has to use Vector instead.

sepp2k
  • 363,768
  • 54
  • 674
  • 675