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
| }
Syntax. The following is the syntax of filter method. Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the list. This method returns the all the elements of list which satisfiles the given condition.
Scala filter is a method that is used to select the values in an elements or collection by filtering it with a certain condition. The Scala filter method takes up the condition as the parameter which is a Boolean value and returns the result after filtering over that condition.
Scala Collections - Array with Range Use of range() method to generate an array containing a sequence of increasing integers in a given range.
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With