Scala collection type for filter
Assume you have a List(1,"1") it is typed List[Any], which is of course correct and expected. Now if I map the list like this
scala> List(1, "1") map {
| case x: Int => x
| case y: String => y.toInt
| }
the resulting type is List[Int] which is expected as well. My question is if there is an equivalent to map for filter because the following example will result in a List[Any]. Is this possible? I assume this could be solved at compile time and possibly not runtime?
scala> List(1, "1") filter {
| case x: Int => true
| case _ => false
开发者_如何学Python | }
Scala 2.9:
scala> List(1, "1") collect {
| case x: Int => x
| }
res0: List[Int] = List(1)
For anyone stumbling across this question wondering why the most-voted answer doesn't work for them, be aware that the partialMap
method was renamed collect
before Scala 2.8's final release. Try this instead:
scala> List(1, "1") collect {
| case x: Int => x
| }
res0: List[Int] = List(1)
(This should really be a comment on Daniel C. Sobral's otherwise-wonderful answer, but as a new user, I'm not allowed to comment yet.)
With regard to your modified question, if you simply use a guard in the case comprising your partialFunction, you get filtering:
scala> val l1 = List(1, 2, "three", 4, 5, true, 6)
l1: List[Any] = List(1, 2, three, 4, 5, true, 6)
scala> l1.partialMap { case i: Int if i % 2 == 0 => i }
res0: List[Int] = List(2, 4, 6)
精彩评论