scala map and flatMap for dummies


a nice and dummy explanation of map and flatMap in scala.


  1. It is a function
  2. you can apply it to list so example
  3. map expects a function as an argument
  4. this function will run on each element of source list and map it to a new value so => x*2) will return the list of each element doubled
  5. the above notation means for each item of the list will call this item x now what do you want to do with that x ( => ) x*2 is what you wanna do with it.


horrible name because it is not only flattening the map but doing another operation inside which  you are not aware by the method name.

  1. flatMap is just like map a function
  2. in addition its result will never be any kind of a hierarchy of collection will never be List of List of List only a List of Ints (no matter how many internal hierarchies you create in the flatMap function), Strings you get the idea.
  3. in addition if any of the top level items results as None will not include it in result, example
  4. example if result is None,None,None then results will practically be empty if result is None,List(List(1,2,3)) then result will just be 1,2,3 without the first None however if result is 1,List(None,1,2,3) result would be 1,None,1,2,3

Picture worth a thousand words