Last active
April 7, 2016 06:47
-
-
Save auramo/ac5a594eb27fcda3f0d8093134c2a9c3 to your computer and use it in GitHub Desktop.
Examples on how Option is handled neatly
This file contains hidden or 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
// 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