arve
09/30/2025, 10:58 AMjava.time.Instant
over kotlinx.datetime. We are leveraging the typealias trick to make Instant
@Serializable.
This has been working just fine up until now, but today i was writing a specific test and came over something surprising:
When using the aliased type inside a @Serializable
data class, it works as expected. But when trying to serialize a naked MyInstant
i get an exception 🤯
typealias MyInstant = @Serializable(InstantSerializer::class) java.time.Instant
@Serializable
data class Test(val i: MyInstant)
fun main() {
val epoch = MyInstant.EPOCH
println(Json.encodeToString(Test(epoch))) // {"i":"1970-01-01T00:00:00Z"}
println(Json.encodeToString(epoch)) // kotlinx.serialization.SerializationException: Serializer for class 'Instant' is not found.
}
CLOVIS
09/30/2025, 11:28 AMtypeOf<T>()
function that is used within encodeToString()
doesn't know about it. Whereas the compiler plugin which generates the @Serializable
data class does see it.arve
09/30/2025, 11:28 AMarve
09/30/2025, 11:28 AMCLOVIS
09/30/2025, 11:28 AM@Serializable
data class Test(val i: @Serializable(InstantSerializer::class) MyInstant)
works but
println(Json.encodeToString(@Serializable(InstantSerializer::class) epoch))
doesn't