Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Seq[Option[T]] to Seq[T]

Tags:

null

scala

I have a collection of Option[T], and now I want to extract values from it. But I also want the new collection to exclude Nones.

val foo = List(None, None, Some(1), None, Some(2))

The first idea came to my mind is map, but it's a little unintuitive.

foo.map(o => o.get) // Exception!
foo.map(o => o.getOrElse(null)).filterNot(_ == null) // List(1, 2), works but not elegant

Is there a simpler way to achieve this behavior?

like image 720
Lai Yu-Hsuan Avatar asked May 22 '13 15:05

Lai Yu-Hsuan


1 Answers

Use flatten method:

scala> val foo = List(None, None, Some(1), None, Some(2))
foo: List[Option[Int]] = List(None, None, Some(1), None, Some(2))

scala> foo.flatten
res0: List[Int] = List(1, 2)

Just to be complete, there is also flatMap method:

foo.flatMap(x => x)

and for-comprehension:

scala> for(optX <- foo; x <- optX) yield x
res1: List[Int] = List(1, 2)

and collect (acts like filter + map):

scala> foo.collect { case Some(x) => x } 
res2: List[Int] = List(1, 2)
like image 76
om-nom-nom Avatar answered Nov 15 '22 22:11

om-nom-nom