KType is Kotlin reflection’s runtime representation of a Kotlin type. It lets reflective code select serializers and validate constructor arguments, including distinctions between numeric types and nullable parameters. section 12.2.5
Selecting a serializer from a KType
fun serializerForType(type: KType): ValueSerializer<out Any?>? = when (type) { typeOf<Byte>() -> ByteSerializer typeOf<Int>() -> IntSerializer typeOf<Boolean>() -> BooleanSerializer else -> null } The function compares a reflected KType with typeOf<T>() results. A deserializer can therefore distinguish Int from Long or Double before passing a value to callBy(). The selected ValueSerializer performs the required checking or conversion. section 12.2.5
This matters when constructing objects reflectively: callBy() requires each value in its argument map to match the corresponding KParameter.type. Supplying the wrong numeric type can otherwise produce an IllegalArgumentException at runtime. section 12.2.5
KType participates in several practical reflection checks:
- Use typeOf<T>() to obtain a runtime KType for a known Kotlin type. section 12.3
- Inspect parameter types when converting JSON values for reflective deserialization. section 12.2.5
- Account for nullable parameters alongside optional parameters when validating required constructor arguments. section 12.2.5
Listing 12.10 Getting a serializer based on the type of the value
fun serializerForType(type: KType): ValueSerializer<out Any?>? =
when (type) {
typeOf<Byte>() -> ByteSerializer
typeOf<Int>() -> IntSerializer
typeOf<Boolean>() -> BooleanSerializer
// ...
else -> null
}
Compare a KType with typeOf<T>() values to map reflected types to built-in serializers. section 12.2.5
