How to write Collection.ofType<T>()?


#1

Hi,

I am trying to write an extension method for Collection that would return elements of some type. The only way I could get it to almost work is this:

  public inline fun <T, R> Collection<T>.ofType(): List<R> {
  return filter{ it is R }.mapTo(ArrayList<R>()) { it as R }
  }

But then, if i have
  val lst : List<Object>

I have to call it with two parameters:
  lst.ofType<Object, String>()

Instead of just
  lst.ofType<String>

How do I make it require only one type argument? Also, if my implementation is bad, please suggest a better way. Thanks in advance.


#2

First of all, generics are erased, so saying "it is R" does essentially nothing. The only way to actually check something is to pass an instance of Class (i.e. javaClass<Foo>()). Generic parameters may easily be inferred then


#3

Completely forgot about that, thanks :) It works! :)