For Comprehension Examples

scala> //#PS:79

scala> //psn > a30 > a40

scala> val subjects = List(  Some("english"), 
     |                       None, 
     |                       Some("physics"), 
     |                       Some("math"),
     |                       None)
subjects: List[Option[String]] = List(Some(english), None, Some(physics), Some(math), None)

scala> // Example 1                       

scala> val filtered = for { 
     |   subjectOption <- subjects
         //***Note here... Exception is not raised when we have None
         //*** Option can be considered as a Special kind of Collection
         //    which can be extracted using 'for comprehension'
     |   subject <- subjectOption 
     | }yield {
     |   subject
     | }
filtered: List[String] = List(english, physics, math)

scala>   
     | // Example 2                     

scala> val filtered = for { 
     |   subjectOption <- subjects
     |   // When subjectOption is None, that value is automatically
     |   // execluded. ***Note here... Exception is not raised when we have
     |   // None
     |   subject <- subjectOption 
     |   if subject == "english" || subject == "math"
     | }yield {
     |   subject
     | }
filtered: List[String] = List(english, math)

scala> 

scala> // Example 3 : Achieves same goal as Example 2, but in a much clean 

scala> //             way

scala> val filtered = for {
     |   // Pattern matching is used here
     |   Some(subject) <- subjects
     |   if subject == "english" || subject == "math"
     | }yield {
     |   subject
     | }
filtered: List[String] = List(english, math)

No comments:

Post a Comment