https://kotlinlang.org logo
#serialization
Title
# serialization
u

ursus

11/17/2023, 1:16 PM
I'm migrating from
Moshi
Copy code
@Serializable
data class User(
    val id: String,
    val name: String,
    val age: Int? = null <-----------
)
Is there a way to configure this, so I don't have to provide default value of null (just have the
age
be optional? It's very error prone
j

jw

11/17/2023, 1:18 PM
What is error prone about it? It's no less error prone than needing to specify the type or the name of each property.
u

ursus

11/17/2023, 1:19 PM
well optionality in language is express by adding
?
to the type, not
? = null
j

Javier

11/17/2023, 1:25 PM
Why the default value should be null and not anything else? It should be the same as setting an empty string for
String
. It would be doing assumptions.
j

jw

11/17/2023, 1:26 PM
The type dictates what's allowed in the serialized form. In this case, it's an integer or a null literal. The default indicates what value to use should the property be absent from the serialized form. They serve different purposes.
You can, for example, make the type non-null with a default of an integer value. That also will allow its absence in the serialized form.
j

Javier

11/17/2023, 1:29 PM
Anyway you can config this behavior to avoid being explicit. https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#explicit-nulls
👍 1
u

ursus

11/17/2023, 1:40 PM
Hmm okay that does make sense, but not really expected coming from other parsers & ios Decodable as well
explicitNulls = false
works, thanks!