This.getClass().newInstance() in Kotlin?



I just wrote my first Kotlin extension method:

fun <T> Collection<T>.reject(fn : (T) -> Boolean) : Collection<T> {

  val result = ArrayList<T>

  for (item in this) {

  if (!fn(item))



  return result }

This was easy :-). Problem is this here:

val result = ArrayList<T>

I want result to be of the same type as this. The hardcoded solution with ArrayList ist just a temporary cludge. So what I need is somthing like this:

val result = this.getClass().newInstance()

but in Kotlin of course. I tried something with typeinfo(), but this didn’t compile or caused an exception. I looked through the docs not to bother people unnecessarily, but couldn’t find something. Some help appreciated ;-).

Regards, Oliver



First of all, getClass() should work as Collection is a Java class.

Regarding typeinfo, it is not yet implemented. I fixed the docs to reflect that. To retrieve a Java class fro a given Kotlin object foo, use “foo.javaClass”


All right, I'm finished with what I was asking this for which is a little collection of extension methods that add Smalltalk-style iterators to the Java collection classes: I didn't know about stdlib when I started working on it otherwise I might have chosen something else. However, it is merely a Kotlin programming exercise anyway. If someone has suggestions how to make better use of some Kotlin features I might have missed I'd be quite interested.

Cheers, Oliver


Great stuff!

Feedback-wise, it would help a lot if the code was published somewhere (github or otherwise).


Okay, here we go:

Cheers, Oliver