Map versus FlatMap on String
dictionary, scala
Solution
The reason for this behavior is that, in order to apply "map" to a String, Scala treats the string as a sequence of chars (`IndexedSeq[String]`). This is what you get as a result of the map invocation, where for each element of said sequence, the operation is applied. Since Scala treated the string as a sequence to apply `map`, that is what `map`returns.
`flatMap` then simply invokes `flatten` on that sequence afterwards, which then "converts" it back to a String
Problem
Listening to the Collections lecture from Functional Programming Principles in Scala, I saw this example: ``` scala> val s = "Hello World" scala> s.flatMap(c => ("." + c)) // prepend each element with a period res5: String = .H.e.l.l.o. .W.o.r.l.d ``` Then, I was curious why Mr. Odersky didn't use a `map` here. But, when I tried map, I got a different result than I expected. ``` scala> s.map(c => ("." + c)) res8: scala.collection.immutable.IndexedSeq[String] = Vector(.H, .e, .l, .l, .o, ". ", .W, .o, .r, .l, ``` I expected that above call to return a String, since I'm `map`-ing, i.e. applying a function to each item in the "sequence," and then returning a new "sequence." However, I could perform a `map` rather than `flatmap` for a `List[String]`: ``` scala> val sList = s.toList sList: List[Char] = List(H, e, l, l, o, , W, o, r, l, d) scala> sList.map(c => "." + c) res9: List[String] = List(.H, .e, .l, .l, .o, ". ", .W, .o, .r, .l, .d) ``` Why was a `IndexedSeq[String]` the return type of calling `map` on the String?