I have a heterogeneous list similar to the following:
val l = List(1, "One", true)
and I need to filter out its objects, extracting only those that belong to this class. For this, I wrote a very simple way:
def filterByClass[A](l: List[_], c: Class[A]) = l filter (_.asInstanceOf[AnyRef].getClass() == c)
Note that I must add an explicit conversion to AnyRef to avoid this compilation problem:
error: type mismatch; found : _$1 where type _$1 required: ?{val getClass(): ?} Note that implicit conversions are not applicable because they are ambiguous: both method any2stringadd in object Predef of type (x: Any)scala.runtime.StringAdd and method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A] are possible conversion functions from _$1 to ?{val getClass(): ?} l filter (_.getClass() == c)
However, in this way the call:
filterByClass(l, classOf[String])
returns as expected:
List(One)
but, of course, this does not work, for example, with Int, since they extend Any, but not AnyRef, therefore, by calling:
filterByClass(l, classOf[Int])
the result is only an empty list.
Is there a way to get my filterByClass method to work even with Int, Boolean and all other classes extending Any?