Another potentially silly question. I've got a J...
# javascript
a
Another potentially silly question. I've got a JS project that defines its "enums" as hardcoded string constants in a big array. I've also got a Kotlin multiplatform project where I redefine those string constants as real `enum class`es and have some methods/classes that take them as inputs and use them as properties. I'm trying to interact with the Kotlin/JS output from the older JS project. I'd like the older JS project to be able to treat the enums as regular string literals when calling those methods accessing them as properties of other classes. Is there a standard way to do this? Here's a gist with a barebones example of what I'm talking about and some more details (including what I've tried and what else I think I can do): https://gist.github.com/ankushg/069c743f7fe40e71afbe67632d98b7bc
a
AFAIK there is no standard way to make Kotlin/JS treat enum classes as strings at the moment.
a
That's what I thought. I'll use `expect`/`actual` to avoid exposing the enums to JS for now then. I saw that 1.3-M1 includes support for inline classes, and was reading through the KEEP when I stumbled across inline enum classes as a use case. https://github.com/Kotlin/KEEP/blob/master/proposals/inline-classes.md#motivation--use-cases
It looks like 1.3-M1's merged support for inline classes doesn't (yet) include support for inline enums, but is that what I should be keeping my eye one for future developments?
a
Probably. Although this particular use case of adapting the JS enum representation could be improved in a number of ways.
For the time being what you could try doing something like this:
Copy code
// common
expect class MyEnumProxy

expect fun MyEnumProxy.resolve(): MyEum

enum class MyEnum {
    A, B
}

// JVM
actual typealias MyEnumProxy = MyEnum
actual inline fun MyEnumProxy.resolve() = this

// JS
actual typealias MyEnumProxy = String

actual fun MyEnumProxy.resolve() = MyEnum.valueOf(this)
I have not tested this, but I think it could work. There will still be boilerplate, but it should have zero overhead on JVM at least.
a
Ah that seems a lot more reasonable than having to modify every public API that uses enums. I'll give it a go. Thanks!
Unfortunately I can't use
expect class
in combination with
actual enum class
(or a typealias to one) -- the compiler marks the declarations as incompatible because the class kinds are different 😞
a
Hm... Maybe an
actual inline class
could work?
a
It looks like that doesn't work either. I can't
actual inline class
without
expect inline class
, and if I
expect inline class
, I need to provide the constructor in common code. This means that I can't use
String
in JS while using
MyEnum
in the JVM
I'll follow the progress of
inline enum class
-- that at least sounds like what I'm trying to do 🙂
a
😃
a
Thanks for the help!