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")))
}
}
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
ribesg
05/18/2022, 1:30 PM
Well that’s on iOS
ribesg
05/18/2022, 1:31 PM
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
ribesg
05/18/2022, 1:32 PM
From time to time it serializes the date, when a ms change occurs right in between the object creation and its serialization
ribesg
05/18/2022, 1:32 PM
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.