https://kotlinlang.org logo
#serialization
Title
# serialization
o

Oleh Havrysh

01/31/2023, 4:33 PM
Hi everybody! I have a problem with with using Kotlin serialization for PersistentList Since it doesn't support serialization I need to implement (or generate) it by myself I went through docs but seems like it's not trivial case because it's both polymorphic (in my case in runtime I have
SmallPersistentVector
which is
internal
BTW) and generic (
<E>
forList items) So what I have now:
Copy code
class PersistentListSerializer<T>(elementSerializer: KSerializer<T>) : KSerializer<PersistentList<T>> {

    private val listSerializer = ListSerializer(elementSerializer)

    override val descriptor: SerialDescriptor = listSerializer.descriptor

    override fun serialize(encoder: Encoder, value: PersistentList<T>) {
        listSerializer.serialize(encoder, value)
    }

    override fun deserialize(decoder: Decoder): PersistentList<T> =
        listSerializer.deserialize(decoder).toPersistentList()
}
I'll have a lot of usages among the UI entities in my app (I use PersistentList for Compose), so wanted to define serializer in the single place where I save the state:
Copy code
private val json = Json {
        serializersModule = SerializersModule {
            polymorphic(PersistentList::class) {
                subclass(SmallPersistentVector::class) // can't access since it's internal
            }

            contextual(PersistentList::class) { PersistentListSerializer(it.first()) } // doesn't work because in runtime it receives SmallPersistentVector, not PersistentList
        }
    }
🧵 1
✔️ 1
p

phldavies

01/31/2023, 5:14 PM
Rather than using a contextual, I found your serializer works fine either brought into the model as
@file:UseSerializers(PersistentListSerializer::class)
or
@Serializable(with = PersistentListSerializer::class)
on the property, or using
typealias SerializablePersistentList<T> = @Serializable(with = PersistentListSerializer::class) PersistentList<T>
as an example
The typealias is probably the better option, unless you’re happy with remembering to specify the
@file:UseSerializers(PersistentListSerializer::class)
in file that defines a
@Serializable
class that uses
PersistentList
o

Oleh Havrysh

02/01/2023, 8:59 AM
@phldavies Thank you! Yeah, the solution with typealias is good for me, now it works
p

pdvrieze

02/01/2023, 2:34 PM
Also, to make things work correctly in all cases you may want to use a serialdescriptor with a new name (IIRC just call
SerialDescriptor
with the new name and base descriptor).
7 Views