For the time being we are forced to use `java.time...
# codereview
a
For the time being we are forced to use
java.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 🤯
Copy code
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.
}
c
The typealias is removed at compile-time, and the
typeOf<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.
a
aah!
thanks, that makes sense
c
Same reason why
Copy code
@Serializable
data class Test(val i: @Serializable(InstantSerializer::class) MyInstant)
works but
Copy code
println(Json.encodeToString(@Serializable(InstantSerializer::class) epoch))
doesn't