1

What is the best way to convert a list of Option[T] to a list of T where the option is not None? E.g. I want to go from this:

scala> val xs = Some(3) :: None :: Some(4) :: Some(5) :: None :: Nil xs: List[Option[Int]] = List(Some(3), None, Some(4), Some(5), None) 

to this:

List[Int] = List(3, 4, 5) 

in the most idiomatic way possible.

0

1 Answer 1

6

You can just do xs.flatten The documentation is here

Converts this list of traversable collections into a list formed by the elements of these traversable collections.

Option is a traversable type and it is biased so traversing the data structure will discard any None values

And fyi null and None are very different things. Your title isn't accurate

What is difference between Null, Nil and Nothing?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.