简体   繁体   English

如何从纯JavaScript数组创建kotlin.collections.Set?

[英]How to create kotlin.collections.Set from plain JavaScript array?

I'm trying to call from plain JavaScript into a Kotlin module that has been compiled into JavaScript. 我正在尝试从普通JavaScript调用已编译为JavaScript的Kotlin模块。 One of the Kotlin methods inside the module requires a kotlin.collections.Set to be passed. 模块内部的Kotlin方法之一需要传递kotlin.collections.Set How can I create such a set object from a plain JavaScript array? 如何从普通的JavaScript数组创建这样的set对象? I've looked into the compiled code, and Kotlin makes internal references to methods like Kotlin.kotlin.collections.setOf_i5x0yv$ but I see no way to call these from outside. 我已经研究了编译后的代码,并且Kotlin对诸如Kotlin.kotlin.collections.setOf_i5x0yv$类的方法进行了内部引用,但是我看不到从外部调用这些方法的方法。

According to the Kotlin documentation Sets are not represented in Javascript. 根据Kotlin文档,集不以Javascript表示。

Arrays on the other hand are mapped. 另一方面,数组是映射的。 Therefore a simple function can be written which maps a Javascript Array into a Kotlin Set. 因此,可以编写一个将Javascript数组映射到Kotlin集的简单函数。

@JsName("createSetFromJsArray")
fun <TValue> createSetFromJsArray(array: Array<TValue>) = array.toSet()

This function can be used when calling a Kotlin function from Javascript like this: 当从Javascript调用Kotlin函数时,可以使用以下函数:

var test = ["a", "b", "c"];
aKotlinFunction(createSetFromJsArray(test));

and a Kotlin function implemented like: 和Kotlin函数的实现方式如下:

@JsName("aKotlinFunction")
fun aKotlinFunction(test: Set<String>) {
    console.log("aKotlinFunction called with param ${test.joinToString()}")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM