[kotlin] fix: enumUnknownDefaultCase's moshi fallback adapters break nullable enum fields
With enumUnknownDefaultCase=true, the moshi kotlin client registers a com.squareup.moshi.adapters.EnumJsonAdapter with withUnknownFallback for every enum (SerializerHelper.addEnumUnknownDefaultCase). EnumJsonAdapter is not null-safe and is registered bare, so optional enum fields break:
- writing a model whose optional enum is unset throws
NullPointerException: value was null! Wrap in .nullSafe() to write nullable values.This includes every JSON request body the generatedApiClientsends; - reading an explicit
nullfor an enum field throwsJsonDataException.
Without the flag, moshi's built-in enum adapter is null-safe, so the flag is a regression for optional enums. Reproduced on current master.
Fix
jvm-common/infrastructure/SerializerHelper.kt.mustache: append .nullSafe() to the registered adapter in both branches (top-level and inline enums).
Tests and samples
KotlinClientCodegenModelTest#testMoshiEnumUnknownDefaultCaseAdaptersAreNullSafegenerates3_0/enum.yamlwith the flag and asserts every registered adapter is wrapped. Fails without the fix.kotlin-enum-default-value, the only moshi sample with the flag, gains.nullSafe()on its five adapters.
PR checklist
- Read the contribution guidelines.
- Built the project and updated samples (
./bin/generate-samples.sh ./bin/configs/kotlin*.yaml). - Technical committee: @jimschubert @dr4ke616 @karismann @Zomzog @andrewemery @4brunu @yutaka0m @stefankoppier
Summary by cubic
Enabling enumUnknownDefaultCase in the Moshi Kotlin client no longer breaks nullable enum fields. Previously, the fallback EnumJsonAdapter was registered bare, so any null enum value threw a NullPointerException on read and write; the adapters are now wrapped with .nullSafe() in both the top-level and inline enum branches.
Tests
- Adds a generator test asserting every registered enum fallback adapter is null-safe.
- Updates the
kotlin-enum-default-valuesample to reflect the new.nullSafe()calls.
Generated with Claude Code