Configure polymorphism styles for sealed classes
mainkaml supports kotlinx.serialization polymorphism for sealed and unsealed types. You can control how types are identified in YAML by setting YamlConfiguration.polymorphismStyle when creating a Yaml instance.
Supported styles:
- YAML tags: Uses
!<tag>to specify the type. - Type property: Uses a dedicated field (e.g.,
type: name) to specify the type.
@Serializable
sealed class Server {
@SerialName("frontend")
@Serializable
data class Frontend(val hostname: String) : Server()
@SerialName("backend")
@Serializable
data class Backend(val database: String) : Server()
}
@Serializable
data class Config(val servers: List<Server>)
val config = Config(listOf(
Frontend("a.mycompany.com"),
Backend("db-1")
))
// This will use the default polymorphism style
val result = Yaml.default.encodeToString(Config.serializer(), config)
println(result)