bigbone
bigbone copied to clipboard
Try to reuse apiName function for serializable enum classes
At some point, we introduced the apiName
function on some enum classes where the serializable name that is expected by the Mastodon API contains characters we cannot recreate in enum class names (such as posting:default:visibility
) and thus cannot easily get the name of those classes by just getting its name.toLowercase()
.
The current approach is as such:
@Serializable
enum class NotificationType {
[…]
@SerialName("update")
UPDATE;
@OptIn(ExperimentalSerializationApi::class)
val apiName: String get() = serializer().descriptor.getElementName(ordinal)
}
That approach works well but we need to add those exact lines for every enum class
where we want that apiName
function.
When implementing a solution for this ticket it would be good if we could reuse the same e.g. extension function so that all enum classes (or at least those enum classes that have the @Serializable
annotation and thus a serializer()
to begin with) automatically.
I would suggest creating an interface that all your serializable enums implement. For example:
interface ApiNamed {
val apiName: String
}
@Serializable
enum class NotificationType : ApiNamed {
@SerialName("update")
UPDATE;
@OptIn(ExperimentalSerializationApi::class)
override val apiName: String
get() = serializer().descriptor.getElementName(ordinal)
}
Otherwise, I think it is possible to create extension function for all enum classes that have the @Serializable
annotation, something like that: https://discuss.kotlinlang.org/t/extension-function-for-enums-of-the-same-shape/17262
@G10xy An interface wouldn’t really solve our problem of repeating ourselves constantly, unfortunately.
An extension function was what I had in mind. I just don’t know yet if it’s possible to create one only for enum classes that also have the @Serializable
annotation but without using reflection. 🤔