https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
s

Sebastian

04/28/2021, 1:06 PM
Hey peeps, I’m trying to use Kotlin-based enums and classes in JavaScript/TypeScript but these objects have mangled fields (e.g.
_category_0
instead of
category
) and lots of unneeded metadata (e.g. the enums’ hash code values) attached. Do I understand it correctly that I need write custom Serializers to turn these objects into more readable/simple JSON objects? Or what’s a good way to approach this? Perhaps there are some other annotations I need to check? Example below: I’m trying to return a list of question objects with some fields (e.g. an enum-based
type
and a list of
options
).
Ideally, the result should be something like this instead:
Copy code
[
  {
    "type": "options",
    "translationKey": "vegetables",
    "category": "diet",
    "options": [
      {
        "translationKey": "some_option",
        "values": {}
      },
      {
        "translationKey": "another_option",
        "values": {}
      }
    ]
  },
  {
    "type": "options",
    "translationKey": "organic",
    "category": "diet",
    "options": [
      {
        "translationKey": "some_option",
        "values": {}
      }
    ]
  },
  {
    "type": "number_input",
    "translationKey": "shortrangeflights",
    "category": "travel"
  }
]
r

russhwolf

04/28/2021, 1:32 PM
If you're using the legacy compiler you probably need
@JsName
annotations. (Or
@JsExport
for the IR compiler, but if you were using that you'd get no output instead of mangled output when it's missing)
s

Sebastian

04/28/2021, 1:37 PM
I’m using the IR compiler and added
@JsExport
to a top-level class that provides a method that returns a list of objects. I’ve also tried adding
@JsName
annotations to the fields but that didn’t change anything (I think the IR compiler doesn’t pick those up?).
r

russhwolf

04/28/2021, 1:41 PM
You might need to
@JsExport
all the way down the hierarchy
I haven't actually done much here though. If that doesn't work you could also ask in #javascript
s

Sebastian

04/28/2021, 1:43 PM
I’d love to use
@JsExport
everywhere but I’m using quite a few enums and it seems to be impossible to use
@JsExport
with enums?
Thanks for your help, @russhwolf! I’ll cross-post this in #javascript soon if I don’t find a solution in the meantime. ✌️
Update: Turns out that returning
Array
instead of
List
is very beneficial for the JS usage (as documented here). And with the proper
@JsExport
annotation on all classes that I want to use inside JS, I can also get the right field names. 🦜
14 Views