Treat nullable fields as optional
See original GitHub issueCurrently if you have a data class that has nullable fields the serializer still considers the fields as required so for example
@Serializable
data class ResponseData(
val id: Long
val email: String?,
val phone: String?,
val text: String
}
I would have expected the nullable fields to be null if they didnt exist in the json response but they throw the MissingFieldException
To fix the error you just set the default value to null
@Serializable
data class ResponseData(
val id: Long
val email: String? = null,
val phone: String? = null,
val text: String
}
To prevent from having to go through every nullable field can we just have it so that if its nullable and no default value set then its also considered optional?
What is the point of even having nullable fields if you have to set a default value anyway (aside from being able to have a null value for the field) for it to be null if the fields does not exist in the json response?
It seems to me something like this would make more sense and be more kotlin like
@Serializable
data class ResponseData(
val id: Long //Required because its not nullable
val email: String?, //Optional
val phone: String? = "123456789", //Optional thats nullable
val text: String //Required because its not nullable
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:10 (3 by maintainers)
Top GitHub Comments
I don’t agree. In Kotlin, if you try to instantiate your first data class example in code, you will have to provide a value for the nullable fields, for they don’t have a default value. So the notion of nullable == optional is not really a Kotlin idiom. Same goes for serialization.
We need a way to differentiate
and
Sometimes, they don’t mean the same thing. Both deserialize to:
but only the former deserializes to:
In other words, “undefined” is not always meant to mean the same as “defined as null”.
@kernitus That’s what the new flag
explicitNulls
(#1535 ) does