2

I have a Kotlin function written that consumes a List<String>. The function has an annotation with @JsName so that I can call this function from 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. Furthermore, the names in the Kotlin standard library are all mangled; so I cannot in any reliable way call say listOf in JavaScript and pass the results to function.

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?

Vance T
  • 513
  • 2
  • 5
  • 15

1 Answers1

2

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.

As you are dealing with List<String>, you may do this in 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.

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.
  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. (I want a more proper way of doing this too)
  3. If you need to deal with a List of custom objects, e.g. of class Foo, you should be able to call new <package>.<identifier>...Foo(params).
Sunny Pun
  • 726
  • 5
  • 14
  • Thank-you, I will look into this soon. I seem to remember all of the kotlin package names were mangled, but maybe there were some I did not notice. Is there some compiler flag you know of that is guaranteeing kotlin.kotlin.collections.* isn't mangled or are class names not mangled? – Vance T Nov 08 '19 at 19:41
  • `kotlin.kotlin.collections.*` is from `kotlin.js` that is generated as a shared library along with the compiled Kotlin source. (I “require” it from NPM) Class names are not mangled but the function names are. – Sunny Pun Nov 08 '19 at 19:46
  • Thanks a lot! I wasn't sure how to convert from an ArrayList to a regular Javascript array. The `toArray()` did the trick! – sebleclerc Jun 01 '20 at 20:50