blue-sky blue-sky - 27 days ago 13
Scala Question

How to filter remove None types from List[(String , Option[Int])]?

Here I'm attempting to remove

None
type from a list of
(String , Option[Int])
where the
None
type can be at position 2 in the tuple :

val l : List[(String , Option[Int])] = List(
("a" , None),
("b" , Option(1)),
("c" , Option(2))
)

val filteredSomes = for {
(e <- l)
if(e._2 >= 0)
} yield e

println(filteredSomes);


But this does not compile :

causes error :

')' expected but '<-' found.
[error] (e <- l)
[error] ^


Can
flatten
be used against this collection instead of for each ?

Answer

Similar to the cheseaux's answer, but more idiomatic:

l.filter(_._2.isDefined)