简体   繁体   English

从JavaScript使用Kotlin标准库

[英]Using Kotlin standard library from JavaScript

I have a Kotlin function written that consumes a List<String> . 我写了一个Kotlin函数,它消耗了List<String> The function has an annotation with @JsName so that I can call this function from JavaScript. 该函数带有@JsName的注释,以便我可以从JavaScript调用此函数。 I cannot determine though what I am supposed to pass into this function. 我无法确定我应该传递给此函数的内容。 Passing an JavaScript Array doesn't work because the Kotlin-JS code calls iterator on the object. 传递JavaScript数组不起作用,因为Kotlin-JS代码在对象上调用了iterator Furthermore, the names in the Kotlin standard library are all mangled; 此外,Kotlin标准库中的名称全部被篡改。 so I cannot in any reliable way call say listOf in JavaScript and pass the results to function. 所以我不能以任何可靠的方式在JavaScript中调用listOf并将结果传递给函数。

The question is then how beyond trivial types (numbers, string, etc.) are we supposed to create and pass to objects functions if the Kotlin standard library names are mangled? 问题是,如果要破坏Kotlin标准库名称,我们应该如何创建普通类型(数字,字符串等)并将其传递给对象函数?

You can use ArrayList when interop with JavaScript in Kotlin, since List is an interface (which isn't in JavaScript) and (one of) its actual implementation is ArrayList . 在Kotlin中与JavaScript互操作时,可以使用ArrayList,因为List是一个接口(JavaScript中没有),并且(其中之一)其实际实现是ArrayList

As you are dealing with List<String> , you may do this in JavaScript: 在处理List<String> ,可以在JavaScript中执行以下操作:

let list = new kotlin.kotlin.collections.ArrayList(["foo","bar","baz"])

And you can pass the list variable to the functions that needs a List<String> parameter. 而且,您可以将list变量传递给需要List<String>参数的函数。

Remarks: 备注:

  1. You can call list.toArray() to convert a List from Kotlin back to JavaScript array, if some of your Kotlin functions returns a List. 如果您的某些Kotlin函数返回List,则可以调用list.toArray()将List从Kotlin转换回JavaScript数组。
  2. I would declare "middleman" (adapter) functions that push an item to a List , that takes a MutableList and call add , since the library function is mangled. 我将声明“中间人”(适配器)函数,该函数将项目推送到List ,该List需要一个MutableList并调用add ,因为该库函数已损坏。 (I want a more proper way of doing this too) (我也想要一种更合适的方法)
  3. If you need to deal with a List of custom objects, eg of class Foo , you should be able to call new <package>.<identifier>...Foo(params) . 如果您需要处理自定义对象的列表,例如Foo类,则应该可以调用new <package>.<identifier>...Foo(params)

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

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