Skip to content

Instantly share code, notes, and snippets.

@auramo
Last active April 7, 2016 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save auramo/ac5a594eb27fcda3f0d8093134c2a9c3 to your computer and use it in GitHub Desktop.
Save auramo/ac5a594eb27fcda3f0d8093134c2a9c3 to your computer and use it in GitHub Desktop.
Examples on how Option is handled neatly
// Map and flatMap for Options/Lists
scala> val myList : List[Option[Int]] = List(Some(1), None, Some(2))
myList: List[Option[Int]] = List(Some(1), None, Some(2))
scala> myList.flatten.map(x=>x*2)
res15: List[Int] = List(2, 4)
scala> myList.flatMap((x) => x.map(_*2))
res16: List[Int] = List(2, 4)
// For comprehension
scala> val listWithOptions: List[Option[Int]] = List(Some(1), None, Some(2))
listWithOptions: List[Option[Int]] = List(Some(1), None, Some(2))
scala> for (theOpt <- listWithOptions; theInt <- theOpt) yield theInt
res29: List[Int] = List(1, 2)
// Now, let's add more nesting!
scala> val deeplyNested: List[List[Option[Int]]] = List(List(None, None, Some(1)), List(), List(Some(2), Some(3)))
deeplyNested: List[List[Option[Int]]] = List(List(None, None, Some(1)), List(), List(Some(2), Some(3)))
scala> for (nestedList <- deeplyNested; theOption <- nestedList; theInt <- theOption) yield theInt
res31: List[Int] = List(1, 2, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment