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


#1

Hello,

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

           result.add(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


#2

Hi,

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”


#3

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: http://www.objectscape.org/stiters/stiters-0.0.1.zip 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


#4

Great stuff!

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


#5

Okay, here we go: https://github.com/oplohmann/stiters

Cheers, Oliver