Toml Content Polymorphic Serializer
abstract class TomlContentPolymorphicSerializer<T : Any>(baseClass: KClass<T>, serialName: String = "TomlContentPolymorphicSerializer<") : KSerializer<T> (source)
Base class for encoding and decoding subclasses of baseClass without a classDiscriminator.
The standard process of polymorphic serialization requires an extra property to denote the underlying type, so that if two subclasses have the exact same properties, it is possible to create an instance with the correct type. However, this is not the common case. Normally different subclasses would just have different properties. In this situation, a special serializer is needed to support serialization without the discriminator.
Example usage:
@Serializable(PlacementSerializer::class)
sealed class Placement {
@Serializable
data object Unplaced : Placement()
@Serializable
data class Placed(val x: Double, val y: Double) : Placement()
}
object PlacementSerializer : TomlContentPolymorphicSerializer<Placement>(
baseClass = Placement::class,
serialName = "Placement" // Optional change.
) {
override fun selectDeserializer(element: TomlElement) = when {
element.asTomlTable().isNotEmpty() -> Placement.Placed.serializer()
else -> Placement.Unplaced.serializer()
}
}
val unplaced = ""
Toml.decodeFromString<Placement>(unplaced) // Unplaced
val placed = """
x = 0.0
y = 0.0
""".trimIndent()
Toml.decodeFromString<Placement>(placed) // Placed(x=0.0, y=0.0)Content copied to clipboard