Js interop question. How do I get a reference to a...
# javascript
s
Js interop question. How do I get a reference to a kotlin class constructor that javascript can call
new
on ?
Copy code
class KotlinClass extends ExternalClass {
    constructor(p1 : Context) : super(p1) {
    }
}
When I pass
KotlinClass::class.js
it will pass the
KotlinClass
in javascript land.. but the
super
call is placed in the
function KotlinClass_init()
which seems to ever only be called from Kotlin. I tried getting a reference to
KotlinClass_init
but doing
::KotlinClass
in kotlin land doesnt work either. I think its because it is wrapped in a function leading to a loss of the
this
value. Ultimately I cannot see how javascript can ever new a Kotlin class that needs to pass parameters to its super constructor. It seems to me that it is a compiler flaw that the kotlin constructor body is not placed in the native javascript constructor instead of this init function.
s
Kotlin can have multiple secondary constructors while JS supports only a single one. Thus all secondary constructors are implemented as separate functions. However
KotlinClass::class.js
should work when using primary Kotlin constructor, instead of a secondary one:
Copy code
class KotlinClass(p1: Context) : ExternalClass(p1) {
}
In these cases, when possible, I prefer wrapping constructor calls with a regular function, so you can call it without
new
from JS:
Copy code
fun createKotlinClass(p1: Context) = KotlinClass(p1)
s
Thank you. That was my first attempt but I must have gotten confused since that turned out not to be my issue.
Turns out we needed to emulate inheritance of statics. Yet another funky part of js interop