- list flatMap {
- case st: String => Some(st)
- case _ => None
- }
At a glance one might wonder why not simply use list.filter{_.isInstanceOf[String]}. The difference is that the flatMap will return a List[String].
However Scala 2.8 offers the collect method for doing a similar thing.
- def strings(list: List[Any]) = list flatMap {
- case st: String => Some(st)
- case _ => None
- }
- // returned list is a List[String]
- scala> strings("hi" :: 1 :: "world" :: 4 :: Nil)
- res11: List[String] = List(hi, world)
- // returned list is a List[Any] (not as useful)
- scala> "hi" :: 1 :: "world" :: 4 :: Nil filter {_.isInstanceOf[String]}
- res12: List[Any] = List(hi, world)
- // collect returns List[String]
- scala> "hi" :: 1 :: "world" :: 4 :: Nil collect {case s:String => s}
- res13: List[String] = List(hi, world)
How about this?
ReplyDeletelist flatMap {x=>Option(x.asInstanceOf[String])}
Madoc, that leads to ClassCastException
ReplyDeletehmm...
ReplyDeletelist flatMap {x => catching[String](classOf[ClassCastException]) {
Some(x.asInstanceOf[String])
}
You can do the same thing with collect, but even simpler because it will ignore anything that doesn't have a case:
ReplyDeletescala> val l = List(1,2,3,4)
l: List[Int] = List(1, 2, 3, 4)
scala> l.collect { case 1 => 1 }
res1: List[Int] = List(1)