I have started learning Scala quite some time back and I did some reading on flatMap
and flatten
from the below two links.
The author takes the below code example,
val fruits = Seq("apple", "banana", "orange")
and then uses flatMap
on it.
fruits.flatMap(_.toUpperCase)
Also, the author says that map
+ flatten
is flatMap
with the below example.
def toInt(s: String): Option[Int] = {
try {
Some(Integer.parseInt(s.trim))
} catch {
// catch Exception to catch null 's'
case e: Exception => None
}
}
val strings = Seq("1", "2", "foo", "3", "bar")
val mapResult = strings.map(toInt)
val flattenResult = mapResult.flatten
In both the examples I am confused on how it differs from flatten
. Let's take the first example.
fruits.flatMap(_.toUpperCase)
This can also be computing using flatten
as below and leading to the same result.
fruits.flatten(_.toUpperCase)
On the second example, it can be achieved with flatten
also,
val flattenMap = strings.flatten(x=>toInt(x))
Since flatten
is also a higher order function that takes in parameters, how is it different from flatMap
?
I can see that the source code is different for both the methods. I didn't dig deeper as I am yet to learn about co-variance, contra variance without which I wouldn't understand the collection source code.
Can anyone state a concrete example of where one would use flatten
and flatMap
?