从Kotlin创建新的节点模块对象

从Kotlin创建新的节点模块对象

本文介绍了从Kotlin创建新的节点模块对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Kotlin中编写一个小型的node.js应用程序,以测试和使用javascript互操作.从一个暴露了原型"Bar"的外部节点模块"foo"中,我试图创建一个"Bar"的新实例.

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'.

在Javascript中,我只会写类似

In Javascript I would simply write something like

var foo = require('foo')
var bar = new foo.Bar()

在Kotlin中,我定义了一个外部函数'require'并加载了按预期工作的模块:

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

现在,我想创建一个Bar的新实例.到目前为止,我已经尝试过:

Now I would like to create a new instance of Bar. So far I've tried:

  • 呼叫val bar = foo.Bar().这被解释为功能,因此不起作用.
  • 定义外部类Bar并创建一个新对象val bar = Bar()
  • 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()

我只能找到的唯一解决方法是通过本机JavaScript代码val bar = js("new foo.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:

  • 它不是类型安全的(这是使用kotlin的优点之一)
  • 它与变量foo有隐式依赖关系,在编译时不会对其进行检查
  • 该模块使用许多不同的构造函数参数公开了许多此类对象,这将导致产生大量如上所述的本机代码,

有什么方法可以实现这一目标,最好是在纯Kotlin中实现?

Is there any way to achieve this, prefearably in pure kotlin?

推荐答案

我想您必须将Bar定义为模块foo中的外部类:

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

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

请参见 https://kotlinlang.org/docs/reference/js-modules. html https://kotlinlang.org/docs/reference/js- interop.html

这篇关于从Kotlin创建新的节点模块对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:07