@Target(allowedTargets = [AnnotationTarget.CLASS])
annotation class Polymorphic(val labelKey: String, val onMissing: Polymorphic.Fallback = Fallback.DEFAULT, val onInvalid: Polymorphic.Fallback = Fallback.DEFAULT)(source)

Annotation to be placed on a sealed class to describe how it should be parsed.

The label key should point out the key in the json to use when figuring out which subtype the json represents. The value can be either a string or a number, in which case it's parsed as a string.

Subclasses use the PolymorphicLabel annotation to indicate which value represents that subtype.

If you want to use a fallback in case the type is invalid or missing you can annotate one of the subtypes with JsonDefaultValue.


@Polymorphic(labelKey = "handType")
sealed class HandOfCards

data class BlackjackHand(val hiddenCard: Card, val visibleCards: List<Card>) : HandOfCards()

data class HoldemHand(val hiddenCards: List<Card>) : HandOfCards()



the key in the json that describes which subtype the object should be decoded as.


defined what happens if labelKey is missing from the JSON.


defined what happens if labelKey is present but invalid (unknown).


Link copied to clipboard

Specifies what happens if the polymorphic label is invalid or missing during parsing of a sealed class.


Link copied to clipboard
Link copied to clipboard
Link copied to clipboard