开发者

Scala: filtering a collection of Options

开发者 https://www.devze.com 2023-04-07 23:45 出处:网络
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:

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 bett开发者_如何学编程er 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]


This should do it:

val bs = as.flatMap(checker)


The answer above is correct, but if you can rewrite checker, I suggest you use PartialFunction and collect. PartialFunction is a function of type A=>B that is not necessary defined for all values of A. Here is a simple example:

scala> List(1, 2, 3, 4, "5") collect {case x : Int => x + 42}
res1: List[Int] = List(43, 44, 45, 46)

collect takes an instance of PartialFunction as argument and applies it to all elements of the collection. In our case the function is defined only for Ints and "5" is filtered. So, collect is a combination of map and filter, which is exactly your case.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号