flatMap (Scala)
Was a little confused on how flatMap works, so writing some notes here.
This stackoverflow gives a good explanation.
flatMap, because flatMap expects the function to return a collection (or a collection-like result, such as Option, List, Seq, etc.).
map
is pretty intuititve.
map
vs.flatMap
- map takes a function and applies it to each element of a sequence, returning a new sequence with the results of the function
- flatMap transforms each element into a collection of elements
On
flatMap
...flatMap expects the function to return a collection (or a collection-like result, such as Option, List, Seq, etc.)
Consider the following Vehicle
class:
If you use .map
, you would get the following results
However, using .flatMap
:
How does that work?
vehicle.name
returns aString
, for example,"Honda"
.- In Scala, a
String
is treated as a collection ofChar
elements (i.e., it is essentially like a sequence of characters).
When you apply flatMap
to a String
, it treats the String
as a collection of characters and flattens those characters into the final result.
What if the function you use to flatMap returns an
Int
?In that case, it wouldn’t work.