4 Replies Last post: May 6, 2012 6:15 PM by Oliver Plow  
Oliver Plow Novice 105 posts since
Mar 17, 2012
Currently Being Moderated

Mar 17, 2012 1:28 PM

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

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

Andrey Breslav Apprentice 929 posts since
Jun 11, 2007
Currently Being Moderated
Mar 17, 2012 1:39 PM in response to: Oliver Plow
Re: this.getClass().newInstance() in Kotlin?

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"

Andrey Breslav Apprentice 929 posts since
Jun 11, 2007
Currently Being Moderated
May 5, 2012 8:29 AM in response to: Oliver Plow
Re: this.getClass().newInstance() in Kotlin?

Great stuff!

 

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

More Like This

  • Retrieving data ...