flatMap i like using map
In practice usage of flatMap naturally occurs in conjuction with Option, Try and Future collections.
Here is an example:
def makeInt(s: String): Try[Int] = Try {
s.toInt
}
val a = makeInt("1")
val b = makeInt("2")
val c = a.map { a1 => b.map { b1 => a1 + b1 } }
This evaluates to : c = Success(value = Success(value = 3))
So if we just use a map we get a result the is of type Try[Try[Int]] which probably isn’t what we want.
val c = a.flatMap { a1 => b.amp { b1 => a1 + b1 } }
This evaluates to Success(value = 3) (Type Try[Int])
So we want to combine two vals of type Try how naturally leads to using flatMap. Similarly when we just Options, Either, and Future we’ll find ourselves using flatMap.