capturedKClass

Retrieves KClass associated with serializer and its descriptor, if it was captured.

For schema introspection purposes, capturedKClass can be used in SerializersModule as a key to retrieve registered descriptor at runtime. This property is intended to be used on SerialKind.CONTEXTUAL and PolymorphicKind.OPEN kinds of descriptors, where actual serializer used for a property can be determined only at runtime. Serializers which represent contextual serialization and open polymorphism (namely, ContextualSerializer and PolymorphicSerializer) capture statically known KClass in a descriptor and can expose it via this property.

This property is null for descriptors that are not of SerialKind.CONTEXTUAL or PolymorphicKind.OPEN kinds. It may be null for descriptors of these kinds, if captured class information is unavailable for various reasons. It means that schema introspection should be performed in an application-specific manner.

Example

Imagine we need to find all distinct properties names, which may occur in output after serializing a given class with respect to @Contextual annotation and all possible inheritors when the class is serialized polymorphically. Then we can write following function:

fun allDistinctNames(descriptor: SerialDescriptor, module: SerialModule) = when (descriptor.kind) {
is PolymorphicKind.OPEN -> module.getPolymorphicDescriptors(descriptor)
.map { it.elementNames() }.flatten().toSet()
is SerialKind.CONTEXTUAL -> module.getContextualDescriptor(descriptor)
?.elementNames().orEmpty().toSet()
else -> descriptor.elementNames().toSet()
}

See also