Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala collection type for filter

Tags:

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
     | }
like image 440
Joa Ebert Avatar asked Feb 07 '10 22:02

Joa Ebert


People also ask

How to filter data in Scala?

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.

How filter works in Scala?

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.

Which of the following method make use of Scala collections?

Scala Collections - Array with Range Use of range() method to generate an array containing a sequence of increasing integers in a given range.

What is a SEQ in Scala?

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.


2 Answers

Scala 2.9:

scala> List(1, "1") collect {
     |   case x: Int => x
     | }
res0: List[Int] = List(1)
like image 92
Daniel C. Sobral Avatar answered Oct 20 '22 04:10

Daniel C. Sobral


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.)

like image 45
Mark Tye Avatar answered Oct 20 '22 04:10

Mark Tye