-
-
Save lucianenache/60a0b82f02facebfecf76fe5bb52314a to your computer and use it in GitHub Desktop.
collect vs map, filter vs flatMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The collect method takes a PartialFunction as argument and maps the | |
// values defined for this partial function over it, skipping those | |
// outside the definition domain. | |
// Given a partial function pf, the following code: | |
// | |
// val pf: PartialFunction[A, B] = | |
// coll.collect(pf) | |
// | |
// is roughly equivalent to | |
// | |
// coll.filter(pf.isDefinedAt _).map(pf) | |
// filter and map returns List[Any] | |
scala> List("hello", 1, true, "world").filter(_.isInstanceOf[String]).map(identity) | |
res0: List[Any] = List(hello, world) | |
// flatMap returns List[String] | |
scala> List("hello", 1, true, "world") flatMap { | |
| case t: String => Some(t) | |
| case _ => None | |
| } | |
res1: List[String] = List(hello, world) | |
// collect returns List[String] and is concise | |
scala> List("hello", 1, true, "world") collect { case s: String => s } | |
res2: List[String] = List(hello, world) | |
// A instance of Seq, Set or Map is actually a partial function. So, | |
scala> val pets = List("cat", "dog", "frog") | |
pets: List[String] = List(cat, dog, frog) | |
scala> Seq(1, 2, 42) collect pets | |
res2: Seq[String] = List(dog, frog) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment