How kotlinx.serialization builds serializers at compile time
Marking a Kotlin class with @Serializable looks simple, but the useful work happens inside the compiler. This guide explains how the plugin creates a serializer, describes its fields, validates required values, and chooses serializers for nested types — without relying on reflection at runtime.
Why compile-time generation replaces reflection
Reflection-based serialization discovers properties and values while the program runs. That adds repeated lookup and getter overhead, behaves differently where reflection support is limited or absent — notably Kotlin/Native and Kotlin/JS — and postpones type and missing-property errors until runtime. Compile-time generation avoids those trade-offs because the generated code already knows each property, its type, and how to read or write it. The illustrative data class and simplified reflection example are in protected modules code0001 and code0002.
Plugin stages from annotation to platform code
The plugin works across the frontend, intermediate representation, and backend stages. During resolution it notices @Serializable types and creates synthetic declarations, including the generated serializer class and companion accessors. During IR generation it creates declarations first and fills in their bodies later. The backend then emits the appropriate platform output, such as JVM bytecode, JavaScript, or a Native binary. Registration conceptually connects synthetic resolution, IR lowering, and the K2/FIR extension point; see protected module code0003. In short: frontend discovery, two-stage IR construction, then platform emission.
Two IR passes: declarations first, bodies second
Generated pieces can refer to one another — for example, a serialize method may call a helper, while deserialize must construct the annotated class. Creating every body immediately would leave some references unresolved. The plugin therefore runs two passes. Pass one creates declarations with empty bodies so all symbols exist. Pass two populates those declarations with implementations that can safely reference the full set. The annotated-class sketch and lowering flow are in protected modules code0004 and code0005. This resembles forward declarations, but the two passes happen inside one compilation.
Anatomy of the generated $serializer class
For an annotated class, the plugin creates a nested singleton serializer implementing GeneratedSerializer. Its descriptor captures the class structure, serialize writes each field through the encoder, deserialize reads fields by index and reconstructs the object, and childSerializers exposes the serializers used by its properties. A companion serializer() function provides the conventional entry point. The Person example and its generated shape are in protected modules code0006 and code0007. A practical checklist when inspecting generated output is: confirm the descriptor lists every field, confirm optional fields have defaults, confirm child serializers match property types, and confirm deserialize validates required fields before construction.
Descriptors make one serializer format-agnostic
SerialDescriptor separates structural metadata from format-specific encoding. It records the serial name, element count, element names, optionality, nested type information, and relevant annotations, including a serial name that may differ from the Kotlin class name. JSON can use names as keys, while a binary format can use indices, without changing the serializer logic. The descriptor construction example is in protected module code0008.
Golden mask: one comparison for required fields
During deserialization, each encountered field sets a bit in a seen mask. A compile-time golden mask contains only the bits for required fields — those without defaults. One bitwise comparison then checks whether every required field appeared. If not, the missing-field error can be derived from the difference between the masks. Classes with more than 32 properties use multiple mask integers. The naive check, single-mask pattern, and multi-mask pattern are in protected modules code0009, code0010, and code0011. For the Person example, name and age are required while email is optional, so only the first two bits belong in the golden mask.
How the plugin chooses a serializer for each property
Serializer selection is resolved during compilation in a defined order: an explicit serializer annotation first, then a contextual serializer, built-in primitive serializers, collection and map serializers built from element serializers, enum serializers, serializers from other @Serializable classes, and finally polymorphic handling for interfaces. If none applies, compilation fails with a no-serializer error. The resolution logic is in protected module code0012. The chosen serializers are also exposed through childSerializers so format code can inspect the full structure.
Custom serializers with defaults for evolving APIs
Custom serializers must honor the same KSerializer contract as generated ones. A sealed-type deserializer can read a type discriminator, dispatch to the matching serializer, and return a default for an unknown type; this helps older clients tolerate new server variants. An enum deserializer can similarly map an unknown string to a default value. Both examples are in protected modules code0013 and code0014. Use defaults deliberately: they improve forward compatibility, but they can also hide genuinely invalid payloads, so log or otherwise surface unknown discriminators and enum values where observability matters.
K1 and K2 share the IR generation core
K1 uses descriptor-based synthetic resolution, while K2 uses FIR-based declaration generation. Both frontends ultimately feed the same IR lowering implementation, so the body-generation logic does not need to be duplicated. The K1 and K2 sketches are in protected modules code0015 and code0016. When debugging a frontend-specific problem, check whether the synthetic $serializer declaration was created; when debugging generated behavior, check the shared IR output.
Conclusion
The design combines compile-time knowledge, format-independent descriptors, and bitmask validation to produce serializers that are type-safe and efficient without reflection. That combination is especially valuable for multiplatform code targeting JVM, JavaScript, and Native, and for custom serializers that must remain compatible as APIs evolve.