https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Michael Langford

02/07/2022, 7:38 PM
Copy code
fun JsonObject.get<reified T : Enum<T>>(key: T): JsonElement {
  return this.get(key.name)
}
Hi there, I'm trying to make a generic function that helps make my json parsing a little easier. I'm trying to make it so I can pass any enum, rather than having to make a specific copy of this method for each of the decoding enums I'm using. It seems I'm messing up the syntax for saying "key is a value of some enum type". This is the only way I'm using this (to get the name of the key item), so I don't actually care if it's reified if I don't need to do so to implement this function. Can anyone steer me towards how to write this correctly? Non generic version:
Copy code
fun JsonObject.get(key: EntryTypeAADeserializer.CodingKeys): JsonElement {
  return this.get(key.name)
}
1
s

Sam

02/07/2022, 7:40 PM
Nearly there, just move the generic parameter before the method name!
Copy code
fun <T: Enum<T>> JsonObject.get(key: T): JsonElement {
  return this.get(key.name)
}
(You don't need the
reified
)
m

Michael Langford

02/07/2022, 7:43 PM
thanks sam!
blob smile 1
3 Views