Is it possible to replace the default serializers ...
# serialization
a
Is it possible to replace the default serializers for existing classes such as ⁠`kotlin.Pair` and ⁠`kotlin.Triple`? First, I attempted to set up custom serializers as contextual, but from what I understand they have a lower priority compared to the compile-time ones. Then, I tried to use typealias but it does not seem to make a difference:
Copy code
typealias Tuple3<A, B, C> = @Serializable(with = CustomTuple3Serializer::class) Triple<A, B, C>
For context, I'm trying to use these serializers in a data class like the one below, so I even wonder if that’s feasible in the first place:
Copy code
@Serializable
data class Value<T>(
    val channel: Long,
    val call: String,
    val args: T, //  Tuple types are used here (Pair, Triple…)
)
👀 1
e
yeah, the annotation doesn't make it into the type
Copy code
typeOf<Value<Triple<A, B, C>>>() == typeOf<Value<Tuple3<A, B, C>>>()
so the reified helper
Copy code
Json.encodeToString(Value(0, "", Triple(a, b, c)))
does the same thing (with the default serializer) whether the value is
Value<Triple<A, B, C>>
or
Value<Tuple3<A, B, C>>
if it's specialized and embedded into another type
Copy code
@Serializable
data class Container(
    val value: Value<Tuple3<String, String, String>>,
)
then the generated
Container.serializer()
will use
CustomTuple3Serializer
correctly
or if you use the non-reified function,
Copy code
Json.encodeToString(
    Value.serializer(CustomTuple3Serializer(serializer(), serializer(), serializer())),
    Value(0, "", Triple(a, b, c)),
)
then it will use the one you specified
a
Thanks a ton, that’s much appreciated