Hello, I am wondering how I can convert a Type tha...
# serialization
j
Hello, I am wondering how I can convert a Type that represents a primitive value, via an interface, into the primitive value for serialization only instead of serializing it as an object? Similar to serializing an enum. Value classes do not work a~s they cannot implement interfaces.~ in this case as I want it to be part of a sealed class hierarchy. For example:
Copy code
interface Value // has semantic meaning beyond primitive types and could be an object in other contexts.

sealed class ValuePrimitives : Value {
  data class ValueInt(val value: Int): ValuePrimitives()
  data class ValueString(val value: String): ValuePrimitives()
}
I tried a custom serializer using the PrimitiveKindSerializer but I end up getting an error:
Serializer for ValueInt of kind INT cannot be serialized polymorphically with class discriminator.
c
Value classes do not work as they cannot implement interfaces.
Value classes can implement interfaces.
Copy code
@JvmInline
value class Bz(val bar: Int) : Comparable<Bz> {
    override fun compareTo(other: Bz): Int =
        bar.compareTo(other.bar)
}
u
Value classes can implement interfaces. But kotlinx serialization cannot auto-generate a serializer that contains the required
type
field because value classes only have a single property
j
ah your right. I just looked back and it was they can’t extend classes and I was trying to use a sealed class that implements the interface
I found a solution though in the mean time, thanks!
Copy code
object Serializer : KSerializer<ValueInt> {
                override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ValueInt") {
                    element("value", serialDescriptor<Int>())
                }
//                override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ValueInt", <http://PrimitiveKind.INT|PrimitiveKind.INT>)
                override fun serialize(encoder: Encoder, value: ValueInt) = encoder.encodeInt(value.value)
                override fun deserialize(decoder: Decoder) = ValueInt(decoder.decodeInt())
            }