Description
What is your use-case and why do you need this feature?
I have the following pattern in many of my projects:
@Serializable
sealed interface Hierarchy {
@Serializable
@SerialName("Type1")
data class Type1(val p1: String) : Hierarchy
@Serializable
@SerialName("Type2")
data class Type2(val p2: String) : Hierarchy
// many other subclasses
I use the @SerialName
basically because I don't want the discriminator to be the full class name, having the full package there makes moving hierarchies to different packages very hard and is usually completely unnecessary since sealed hierarchies need to be in the same package anyway (and even when that constraint is relaxed, it's going to be very unlikely to have 2 members of the same hierarchy with the same simple name and that differ by the package name only).
Describe the solution you'd like
I think the default discriminator should have been the simple class name to begin with, but that ship has sailed, so I propose now we introduce a configuration at the Format
level where we could define the default behavior.
Example:
internal val format: StringFormat = Json {
classDiscriminatorDefaultValue = { kClass: KClass<*> ->
kClass.simpleName
}
}
This would:
- Really save me a lot of time, as I would not need to add
@SerialName
to every single member of all my sealed hierarchies, and - Prevent mistakes such as
@SerialName("Type3Something") data class Type3(...
which I made more times that I would like to admit and are very hard to fix as there's data out there with the wrong discriminator.