Create new node module object from kotlin

2019-07-09 09:03发布

问题:

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?

回答1:

I guess you have to define Bar as an external class from module foo:

@JsModule("foo")
external class Bar {
   ...
}

See https://kotlinlang.org/docs/reference/js-modules.html and https://kotlinlang.org/docs/reference/js-interop.html