0

I'm unable to use createInstance(). For example, Foo::class.createInstance()

I have a gradle project using Kotlin 1.3.70 kotlin("jvm") version "1.3.70" plugin. and have implementation(kotlin("stdlib-jdk8")) and implementation(kotlin("reflect")) in my dependencies.

Does anyone know why this function appears to be missing?

I have a function that receives a classType: KClass<Foo> and I want to create a instance of Foo using the noarg constructor.

  • You need a Java Class instance instead of a kotlin class instance: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/java-class.html – PiRocks Apr 23 '20 at 19:07
  • 1
    Are you actually looking for `createInstance()`? – Tenfour04 Apr 23 '20 at 19:08
  • @Tenfour04 Oops yes, that is what I meant I just made a mistake when I wrote the post. –  Apr 23 '20 at 21:02

2 Answers2

0

To use Java reflection (like newInstance()) you need to access the corresponding Java class:

fun createInstance(classType: KClass<Foo>): Foo = classType.java.newInstance()

But Kotlin provides createInstance() as better alternative for that use case:

Creates a new instance of the class, calling a constructor which either has no parameters or all parameters of which are optional.

fun createInstance(classType: KClass<Foo>): Foo = classType.createInstance()
Marvin
  • 13,325
  • 3
  • 51
  • 57
  • Sorry for the mistake, my original post meant to ask why I couldn't use `createInstance()`, I just accidentally wrote `getInstance()` –  Apr 23 '20 at 21:04
  • And that means... what? Sorry, now I no longer understand what your actual question is. – Marvin Apr 23 '20 at 21:36
0

I updated the Kotlin plugin version and deleted by gradle cache and now it seems to be working.