I'm trying to write a small node.js application in Kotlin to test and play with the javascript interop. From an external node module 'foo' which exposes a prototype 'Bar', I am trying to create a new instance of 'Bar'.
In Javascript I would simply write something like
var foo = require('foo')
var bar = new foo.Bar()
In Kotlin, I defined an external function 'require' and load the module which works as expected:
external fun require(module: String): dynamic
...
val foo = require("foo")
//Somehow create a new Bar
Now I would like to create a new instance of Bar. So far I've tried:
- Calling
val bar = foo.Bar()
. This is interpreted as function and thus doesn't work. - Defining an external class Bar and creating a new object
val bar = Bar()
The only workaround I could find is to instantiate the object via native javascript code: val bar = js("new foo.Bar()")
. This works, but has a few disadvantages:
- it is not typesafe (which is part of the beauty of using kotlin)
- it has an implicit dependency on the variable foo which is not checked at compile time
- The module exposes many such objects with different sets of constructor parameters, which would result in a lot of native code as above, which I would like to avoid
Is there any way to achieve this, prefearably in pure kotlin?