kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Add kotlin.time.Instant serializers

Open dkhalanskyjb opened this issue 9 months ago • 5 comments

Can be merged after moving to Kotlin 2.1.20, which introduces kotlin.time.Instant.

kotlinx.datetime.Instant entered the stdlib as kotlin.time.Instant, and so kotlinx.serialization takes over its serializers. See https://github.com/Kotlin/KEEP/pull/387

dkhalanskyjb avatar Mar 04 '25 16:03 dkhalanskyjb

For InstantSerializer to be picked by the compiler automatically, it should be added to this list: https://github.com/JetBrains/kotlin/blob/ab7d84b1ff9fd99c4035fc1c65f9ae7d50a10aa4/plugins/kotlinx-serialization/kotlinx-serialization.common/src/org/jetbrains/kotlinx/serialization/compiler/resolve/NamingConventions.kt#L215

sandwwraith avatar Mar 04 '25 16:03 sandwwraith

For now, you can use serializer(typeOf<Instant>()) to force runtime lookup instead of the intrinsic one. Do not forget to add smth like // serializer<Instant>() TODO: uncomment in 2.1.20

sandwwraith avatar Mar 04 '25 16:03 sandwwraith

Something like this? https://github.com/JetBrains/kotlin/pull/5412

dkhalanskyjb avatar Mar 05 '25 07:03 dkhalanskyjb

Note that even after merging Kotlin PR, changes in this one are required, because compiler is not updated instantly

sandwwraith avatar Mar 06 '25 11:03 sandwwraith

Sure thing! Are there any other changes I should make in addition to that? For example, I copied the test from kotlinx-datetime directly, without trying to adjust its structure to that of surrounding tests, and I'm not sure that I've even put it in the right place.

dkhalanskyjb avatar Mar 06 '25 12:03 dkhalanskyjb

Any chance to get a review (and a release) soon?

hfhbd avatar Jun 22 '25 11:06 hfhbd

@valeriyo

and now what?

Use Instant.serializer() from the package kotlinx.serialization.builtins: https://github.com/Kotlin/kotlinx.serialization/blob/master/core/commonMain/src/kotlinx/serialization/builtins/BuiltinSerializers.kt#L272

hfhbd avatar Jul 06 '25 19:07 hfhbd

@valeriyo,

kotlin.time.Instant isn't annotated.

It's not annotated for the same reason Long and Int isn't: the compiler automatically uses the required serializer if kotlinx.serialization 1.9.0 is present. The IDE may highlight the code as red, but it should still compile.

dkhalanskyjb avatar Jul 07 '25 07:07 dkhalanskyjb

@valeriyo, please share a sample project where the issue happens. I couldn't make it reproduce during testing (https://github.com/Kotlin/kotlinx.serialization/issues/3026#issuecomment-3018700470).

dkhalanskyjb avatar Jul 07 '25 17:07 dkhalanskyjb

@valeriyo, the project you linked compiles without errors and the reason why IDE highlights the code despite it being perfectly fine was described here: https://github.com/Kotlin/kotlinx.serialization/issues/3026#issuecomment-3018712811.

fzhinkin avatar Jul 07 '25 21:07 fzhinkin