user2302244
user2302244

Reputation: 935

Filter for various scala types

I am trying to get a function that will take a 'type' as a parameter and then return all occurrences of that type.

val a = List(1 , 2 , true, "Hello")

def f(a: List[Any], b: ???): List[Any] = {
  a.filter(p => p.isInstanceOf[b])
}

f(a,???)

So that f(a,Int) would return List(1, 2)

Upvotes: 0

Views: 66

Answers (2)

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6172

NOTE: Using deprecated Manifest. See accepted answer for way forward.

Try:

def f [T:Manifest](a: List[Any]): List[T] = a.collect {case x: T => x}

Which you can then use like this:

val filteredList = f[Int](a)

Keep in mind, a List[Any] is almost always a bad idea. There's probably a better way to solve the problem, depending on what you're trying to accomplish.

Upvotes: 2

elm
elm

Reputation: 20405

Consider ClassTag as follows,

def f[T: scala.reflect.ClassTag](xs: List[Any]) = xs.collect { case v: T => v  }

Hence

f[Int](xs)
res: List[Int] = List(1, 2)

Note ClassTag is of interest in collections whose elements type(s) are unknown at compile time.

Upvotes: 3

Related Questions