is there some kind of gotcha I need to know about ...
# javascript
c
is there some kind of gotcha I need to know about when it comes to using enum class values as map keys? 🧵 EDIT: I was using JSON.parse to parse an external interface with kotlin enum class type fields. Nothing exploded, and introspecting the keys made it seem like I was legitimately getting enum values out.
I have some code like:
Copy code
val someMap: Map<EnumClass, String>
someMap[EnumClass.Value] = "boop"
console.log("${someMap[EnumClassValue]} ${someMap[someMap.keys.first()]}") // Prints "null boop"
I'm generating the map using the
associate
function on a collection of items though. I'm going to try this small example though just to see if I get the same result (because that's what I should have done already, d'oh!)
hmm, the following test passes:
Copy code
@Test
    fun canCreateMapWithEnumValue() {
        val someMap: MutableMap<EnumClass, String> = mutableMapOf()
        someMap[EnumClass.Value] = "boop"
        val output = "${someMap[EnumClass.Value]} ${someMap[someMap.keys.first()]}"
        assertEquals("boop boop", output)
    }
I must be doing something stupid
well, I was right, I was being stupid- I need to use kotlinx.serialization I'm guessing. I was foolishly assuming JSON.parse would understand my enum values (it's javascript not kotlin, doh)
c
You'll have the same problem with JSON.parse with any non-primitive values, not just enums: it deserializes the fields, but doesn't actually make the object belong to its original class. It's a problem for all JS-based languages, even for TS: https://stackoverflow.com/a/40512411/5666171
Indeed, KotlinX.Serialization will do this cleverly for you. Not sure if there are other solutions.