Search code examples
scalascala-collectionsscala-option

How to transform Scala collection of Option[X] to collection of X


I'm starting to explore Scala, and one of the things I'm intrigued by is the Option type and the promise of being able to eliminate null related errors.

However I haven't been able to work out how to transform a list (or other collection) of, say, Option[String], to a collection of String (obviously filtering out any values that are None).

In other words, how do I get from this:

List[Option[Int]] = List(Some(1))

... to this:

List[Int] = List(1)

I'm using Scala 2.8 if that has any impact on the answer.


Solution

  • val list1 = List(Some(1), None, Some(2))
    val list2 = list1.flatten // will be: List(1,2)