What is the difference between the map
and flatMap
functions of Iterable
?
Iterable: A base trait for iterable collections. This is a base trait for all Scala collections that define an iterator method to step through one-by-one the collection's elements. [...] This trait implements Iterable's foreach method by stepping through all elements using iterator.
An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other.
Unlike operations directly on a concrete collection like List , operations on Iterator are lazy. A lazy operation does not immediately compute all of its results.
An Iterable is a collection of elements that can be accessed sequentially. In Dart, an Iterable is an abstract class, meaning that you can't instantiate it directly. However, you can create a new Iterable by creating a new List or Set .
The above is all true, but there is one more thing that is handy: flatMap
turns a List[Option[A]]
into List[A]
, with any Option
that drills down to None
, removed. This is a key conceptual breakthrough for getting beyond using null
.
Here is a pretty good explanation:
http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2
Using list as an example:
Map's signature is:
map [B](f : (A) => B) : List[B]
and flatMap's is
flatMap [B](f : (A) => Iterable[B]) : List[B]
So flatMap takes a type [A] and returns an iterable type [B] and map takes a type [A] and returns a type [B]
This will also give you an idea that flatmap will "flatten" lists.
val l = List(List(1,2,3), List(2,3,4)) println(l.map(_.toString)) // changes type from list to string // prints List(List(1, 2, 3), List(2, 3, 4)) println(l.flatMap(x => x)) // "changes" type list to iterable // prints List(1, 2, 3, 2, 3, 4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With