kaml icon indicating copy to clipboard operation
kaml copied to clipboard

Prepare fix for contextual deserialization of polymorphic scalars

Open Jojo4GH opened this issue 5 months ago • 1 comments

Second bug from https://github.com/charleskorn/kaml/pull/607 (as preparation for the PR)

Previously it was not possible to implement a content based polymorphic serializer in the case that one of the types involved is a scalar. Different from the JSON serialization library it was therefore impossible to implement something like:

myCats:
  myFirstCat: "Bella"
  mySecondCat:
    name: "Daisy"
    age: 2
typealias MyCats = Map<String, CatDetails>

@Serializable(with = MyContentBasedSerializer::class)
sealed interface CatDetails {

    @Serializable
    value class InlineName(val name: String) : CatDetails

    @Serializable
    data class More(
        val name: String,
        val age: String?
    ) : CatDetails
}

object MyContentBasedSerializer : YamlContentPolymorphicSerializer<CatDetails>(CatDetails::class) {
    override fun selectDeserializer(node: YamlNode) = when (node) {
        is YamlScalar -> CatDetails.InlineName.serializer()
        is YamlMap -> CatDetails.More.serializer()
        else -> error("Unsupported node type ${node::class.simpleName}")
    }
}

Jojo4GH avatar Sep 16 '24 08:09 Jojo4GH