Using Kotlin Default Parameter Values when JSON value is null and Kotlin parameter type is Non-Nullable
See original GitHub issueI’ve got the following simplified JSON example, which I’m trying to decode into the simplified Kotlin Data Class below.
{
"boolField": null,
"stringField": null
}
data class TestObject(
val boolField: Boolean = true,
val stringField: String = "default"
)
The key thing here is that the Kotlin properties are not nullable, but there is a known default value for them. However, the JSON sometimes contains null
for those fields.
I am trying to get the example JSON to decode using the default values in place of the nulls since the type is non-nullable. However, this doesn’t work out of the box, instead throwing a MissingKotlinParameterException
.
I had a look at modifying the code with a feature flag to behave the way I wanted. This was easy enough to do with some minor alterations to createFromObjectWith()
in KotlinValueInstantiator
for the String
case. However, for the Boolean
case it does not work, as in Java, that non-optional Boolean becomes a boolean
primitive type, which cannot take null
and thus Jackson Data Binding sets it with the default value of false
.
So, assuming I haven’t missed the point completely with this, I’m wondering if there’s a way in the KotlinValueInstantiator
to know that the primitive types were set with their default values by Jackson Data Binding in order to make this work for primitive types too?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:26
- Comments:37 (13 by maintainers)
expected behavior (at least for me):
null
to a non-nullable variable (e.g.String
) if variable has default value, use it. otherwise throw exceptionnull
to a nullable variable (e,g, ‘String?’) set tonull
regardless if there is a default value or not (as the developer has explicitly declared thatnull
is acceptable).not a good solution as many developers are using 3rd party APIs which they have no control over
Branch 2.10 now allows
null
to be treated as “use the default” value, but requires that you set a flag when creating the Kotlin module, otherwise the behavior stays as it was as the default behavior.