Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

Thanks!

like image 677
Gregor Scheidt Avatar asked Sep 28 '11 07:09

Gregor Scheidt


People also ask

How to filter a list in Scala?

Scala List filter() method with example. The filter() method is utilized to select all elements of the list which satisfies a stated predicate. Return Type: It returns a new list consisting all the elements of the list which satisfies the given predicate.

How does filter work in Scala?

Scala filter is a method that is used to select the values in an elements or collection by filtering it with a certain condition. The Scala filter method takes up the condition as the parameter which is a Boolean value and returns the result after filtering over that condition.

How do I use options in Scala?

The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.


1 Answers

This should do it:

val bs = as.flatMap(checker)
like image 170
Kim Stebel Avatar answered Oct 29 '22 17:10

Kim Stebel