George
11/04/2022, 10:39 AM@file:UseSerializers(UrlSerializer::class)
// using serializer explicitly works
val url = URL("<https://test>")
val protobytes = ProtoBuf.encodeToByteArray(UrlSerializer, url)
val result = ProtoBuf.decodeFromByteArray(UrlSerializer, protobytes)
// use file serializer, this fails
shouldThrow<SerializationException> {
val protobytes2 = ProtoBuf.encodeToByteArray(url)
val result2: URL = ProtoBuf.decodeFromByteArray(protobytes)
println(result2)
}
// use typealias serializer, this also fails
shouldThrow<SerializationException> {
val url2: UrlAsString = url
val protobytes2 = ProtoBuf.encodeToByteArray(url)
val result2: UrlAsString = ProtoBuf.decodeFromByteArray(protobytes)
println(result2)
}
// using inside data class works (like in the guide)
@Serializable
data class TestUrl(val value: URL)
val testUrl = TestUrl(url)
val proto = ProtoBuf.encodeToByteArray(testUrl)
val resultUrl: TestUrl = ProtoBuf.decodeFromByteArray(proto)
println(resultUrl)
In case, when using file serializer or global how come it throws: cannot find serializer for URL ?George
11/04/2022, 10:40 AMpublic typealias UrlAsString = @Serializable(UrlSerializer::class) URL
public object UrlSerializer : KSerializer<URL> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URL", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: URL) {
encoder.encodeString(value.toExternalForm())
}
override fun deserialize(decoder: Decoder): URL {
return URL(decoder.decodeString())
}
}
ephemient
11/04/2022, 4:17 PM@file:UseSerializers
only affects the use of URL
in @Serializable
classes. it's not persisted anywhere that the reified helper can look up (and it doesn't know what file you're in). also typealiases don't really exist after being substituted so that's not surprising.