Invoking constructors in Kotlin JS reflectively

Hi,

Given I have a reified generic T that represents a JS class, how can I instantiate it? I essentially want something like js("new ${T::class.js}()"), but naturally that doesn’t work with js. Suggestions?


Before you jump with “you’re doing it wrong”, I’m trying to access svelte components from Kotlin. For each component you make it generates a class, and each class takes the same options. But I’d really rather not copy-paste these arguments to every one of my external class definitions, so instead I’m trying to create a svelteComponent<T>(arg1, arg2) helper method that can do that for me. But to do that, I need to be able to instantiate that T with arg1 and arg2, which is proving a bit tricky.

Thanks!

Try this

open class Base
class Implementation : Base()

inline fun <reified T : Any> makeInstance(): T {
    val constructor = T::class.js
    return js("new constructor()") as T
}


fun main(args: Array<String>) {
    val instanceOfBase = makeInstance<Base>()
    val instanceOfImplementation = makeInstance<Implementation>()

    js("console.log(instanceOfBase)")
    js("console.log(instanceOfImplementation)")
}

output:

//Base
//  __proto__:
//      constructor:ƒ Base()
//      __proto__:Object

//Implementation
//  __proto__:Base
//      constructor:ƒ Implementation()
//      __proto__:Object
2 Likes

@nanodeath how did this work out for you? do Svelte and Kotlin work well together?

I don’t think this particular thing worked out – js("new constructor()") isn’t a valid invocation. But yeah, overall I’m pleased with how Svelte and Kotlin are working together. Pity I have to write JS inside the Svelte components, but for any “heavy lifting” I can hoist some parts up to Kotlin and just call it from the component.