In Scala, the flatMap
method is a higher-order function that is used to transform a collection of collections into a single collection. It is similar to the map method, but it also flattens the resulting collection.
The flatMap
method takes a function as an argument, and applies this function to each element in the collection, returning a new collection with the results. The key difference between map
and flatMap
is that flatMap expects the function to return a collection, whereas map expects the function to return a single value.
Here is an example of using flatMap to flatten a list of lists:
val listOfLists = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
val flatList = listOfLists.flatMap(x => x)
// flatList is now List(1, 2, 3, 4, 5, 6, 7, 8, 9)
In this example, the flatMap
method is applied to the listOfLists
variable, which is a list of lists. The function passed to flatMap
simply returns the original list, effectively flattening the outer list.
Another example, let's say we have a list of options, and we want to extract the values of the options that are not None
:
val list = List(Some(1), None, Some(2), None, Some(3))
val flatList = list.flatMap(x => x)
// flatList is now List(1, 2, 3)
Here, the function passed to flatMap
simply returns the value of the option, effectively discarding the None
values and extracting the values of the Some
options.
In summary, flatMap
is a powerful function that can be used to flatten nested collections, filter out unwanted elements, or extract values from options, among other things. It can be used in combination with other functional programming constructs such as map
, filter
, and fold
to create concise, expressive, and functional code.