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.
czuckie
05/01/2023, 10:11 AM
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"
czuckie
05/01/2023, 10:13 AM
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!)
czuckie
05/01/2023, 10:16 AM
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
czuckie
05/01/2023, 10:23 AM
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
CLOVIS
05/02/2023, 8:02 AM
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
CLOVIS
05/02/2023, 8:03 AM
Indeed, KotlinX.Serialization will do this cleverly for you. Not sure if there are other solutions.