Search code examples
scaladictionaryfilterscala-option

Scala: filtering a collection of Options


Say I have a function that checks whether some operation is applicable to an instance of A and, if so, returns an instance of B or None:

   def checker[A,B]( a: A ) : Option[B] = ...

Now I want to form a new collection that contains all valid instances of B, dropping the None values. The following code seems to do the job, but there is certainly a better way:

   val as = List[A]( a1, a2, a3, ... )
   val bs = 
     as
     .map( (a) => checker(a) )    // List[A] => List[Option[B]]
     .filter( _.isDefined )       // List[Option[B]] => List[Option[B]]
     .map( _.get )                // List[Option[B]] => List[B]

Solution

  • This should do it:

    val bs = as.flatMap(checker)