Map versus FlatMap on String

后端 未结 5 1672
无人共我
无人共我 2020-12-02 16:12

Listening to the Collections lecture from Functional Programming Principles in Scala, I saw this example:

scala> val s = \"Hello World\"

scala> s.flat         


        
5条回答
  •  猫巷女王i
    2020-12-02 16:38

    With map you are taking a list of characters and turning it into a list of strings. That's the result you see. A map never changes the length of a list – the list of strings has as many elements as the original string has characters.

    With flatMap you are taking a list of characters and turning it into a list of strings and then you mush those strings together into a single string again. flatMap is useful when you want to turn one element in a list into multiple elements, without creating a list of lists. (This of course also means that the resulting list can have any length, including 0 – this is not possible with map unless you start out with the empty list.)

提交回复
热议问题