Is there any way to export kotlin enums? Specially...
# javascript
a
Is there any way to export kotlin enums? Specially in Kt/Multiplatform, should we create js-specific wrapper class for function accepting enum as string, or any better (hacky 😜) way?
3
👍 1
a
Wondering about the same. Pretty frustrating to deal with enums from Kotlin/JS
t
Many hacky ways exist I IR even more
Do you use IR? Do you need definitions support?
a
@turansky do you know of a way that supports IR and TS definitions? That’s currently my biggest blocker for IR
t
It depends on your case. In most cases Gradle or Compliler plugin is solution. Do you have examples of input and required output?
a
Right now we have something like
enum class ZeroOrTen(val value: Int) { ZERO(0), TEN(10)}
Ideally we would like this to be interoperable with TS in a way that lets clients use 0 and 10 in place of an instance of the class. We currently use Serialization and custom serializers for this but it’s very heavy for client-side JS. If that’s not possible, maybe • expose named constants that point to the enum class instances • use the value field to automatically define a TS enum or union type that we can pass into a function to get an instance of the actual enum class by the value Currently we can’t even export a function that takes an int and returns an enum because the enum return type can’t be exported.
a
Has been prototyping with taking mobile common code to the Web. @JsExport and JS/TS interop in general is in an early WIP state — the basic works, but is not yet advanced enough to take production code hassle-free. Generating or manually writing exportable JS API wrapper seems to be the only satisfactory solution at the moment. Even if you get around enum classes & other compilation e rror, there are still plenty of issues at runtime awaiting, like https://youtrack.jetbrains.com/issue/KT-45727. I prototyped codegen using KSP + KotlinPoet, and it seems promising. Codegen's pragmatic bonus point IMO: • Don't need to wait for @JsExport to catch up; seems like it is gonna be a long way for stablization before new features even land • Can contain patches/workarounds of these interop issues, without polluting common code • Can rewrite select interfaces and (data) classes into
external interface
, and turn classes into plain JS objects at the API boundary. Useful for React & Web Worker interop. • Likewise, can rewrite enum classes into e.g. a sealed class hierarchy, or
String
+ generated constants indeed. • Rewrite suspend methods into
Promise<T>
returning. • Rewrite
List<T>
to
Array<T>
, etc Still using manually written wrapper code though. Waiting for the web folks' feedback and decision.
2
a
@Anders -- all of those things sound like things that I'm looking for. Please let me know if there's any way I can contribute to the codegen project!
t
Webpack 4+ will inline values
228 Views