Skip to content

Instantly share code, notes, and snippets.

@akirillov
Created August 5, 2016 15:46
Show Gist options
  • Save akirillov/2cd6c5e8d8c4525d5bda7ac0002536bd to your computer and use it in GitHub Desktop.
Save akirillov/2cd6c5e8d8c4525d5bda7ac0002536bd to your computer and use it in GitHub Desktop.
//Let's say we have a list of Ints and function f from Int to Option:
val list = (1 to 10).toList
//List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val f = (x: Int) => if (x%2==0) Some(x*2) else None
//f: Int => Option[Int]
//Now I'm going to apply f to the elements of the list and filter out empty results:
list map f flatten
//List(4, 8, 12, 16, 20)
//Map with flatten is simply a flatMap, so let's try to use it:
list flatMap f
//14: error: type mismatch;
// found : Int => Option[Int]
// required: Int => scala.collection.GenTraversableOnce[?]
//Not surprisingly there's a type mismatch, but if I try to specify an anonymous function
//in flatMap it starts working!!!
list flatMap {x => if (x%2==0) Some(x*2) else None}
//List(4, 8, 12, 16, 20)
//The reason for this is that there's an implicit conversion in Option's companion object
//which converts Option to Iterable so that it satisfies flatMap contract
implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment