First I'll post the code
@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = UUID::class)
object UUIDserializer : KSerializer<UUID> {
override fun deserialize(decoder: Decoder): UUID = UUID.fromString(decoder.decodeString())
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: UUID) {
encoder.encodeString(value.toString())
}
}
typealias SID = @Serializable(with = UUIDserializer::class) UUID
fun randomSid() = UUID.randomUUID() as SID
@Serializable
data class Example(val id:SID = randomSid())
class SerializeId {
@Test
fun nestedTypeUsage() {
val example = Example()
val string = Json.encodeToString(example)
println(string)
}
@Test
fun directTypeUsage () {
val hi = randomSid()
val string = Json.encodeToString(hi)
println(string)
}
}
nestedTypeUsage run and passes, but directTypeUsage fails.
Serializer for class 'UUID' is not found. Mark the class as @Serializable or provide the serializer explicitly. kotlinx.serialization.SerializationException: Serializer for class 'UUID' is not found
I can't apply the @Serializable annotation directly to a val or a function parameter.
almost immediately after posting this. I realized I can
@Test
fun directTypeUsage () {
val hi = randomSid()
val string = hi.toString()
println(string)
}