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:

class Vehicle(val name: String, val model: String, val age: Int, val color: String)
 
val vehicles = Seq(
  new Vehicle("Honda", "Civic", 2023, "Red"),
  new Vehicle("Toyota", "Corolla", 2022, "Blue"),
  new Veh

If you use .map, you would get the following results

val vehicleNames = vehicles.map(vehicle => vehicle.name)
println(vehicleNames)
// List(Honda, Toyota, Suzuki)

However, using .flatMap:

val vehicleParts = vehicles.flatMap(vehicle => vehicle.name)
println(vehicleParts)
 
// List(H, o, n, d, a, T, o, y, o, t, a, S, u, z, u, k, i)

How does that work?

  • vehicle.name returns a String, for example, "Honda".
  • In Scala, a String is treated as a collection of Char 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.