You can use flatMap
(the full method signature in 2.7 is def flatMap[B](f : (A) => Iterable[B]) : List[B]
). It is declared on both Iterable
and Iterator
(with slightly different signatures):
scala> val l = List("1", "Hello", "2")
l: List[java.lang.String] = List(1, Hello, 2)
scala> val ints = l.flatMap { s => try { Some(s.toInt) } catch { case _ => None } }
ints: List[Int] = List(1, 2)
In the above example I'm taking advantage of an explicit conversion option2iterable
in Predef
. It's declared in 2.8 on TraversableLike
:
def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That