Beware of the default behavior on default values! ...
# serialization
r
Beware of the default behavior on default values! It can lead to very unexpected results…
Copy code
@Serializable
    data class Event(
        val id: String,
        val date: Date = Date.now(),
    )

    @Test
    fun test() {
        repeat(100) {
            println(Json.encodeToString(Event("Test")))
        }
    }
Copy code
…
{"id":"Test"}
{"id":"Test"}
{"id":"Test","date":"2022-05-18T10:00:47.011Z"}
{"id":"Test"}
{"id":"Test"}
{"id":"Test"}
…
😱 3
😯 2
n
I'd assume this (the nondeterministic behavior) is a bug with the Kotlin/JS implementation--it doesn't do this on the JVM. Have you reported it?
r
Well that’s on iOS
And I don’t think it’s nondeterministic. It just depends on how fast the serialization occurs after the object creation. If it’s less than a millisecond, then the value is equal to the “default value” of now (in ms) and is not serialized
From time to time it serializes the date, when a ms change occurs right in between the object creation and its serialization
I don’t think it’s a bug, it’s just that when the default value isn’t one single absolute value, but rather the result of a function call which can provide different result based on context (like current time or anything really), then the default behavior of not serializing default values if VERY bad.
n
Oh, that makes sense. And yes, that's very bad.