I'm trying to create a Serializer for the List<Pair<String, Any>> type, I need this type for a project where I have to manipulate keys and values but user can change key names at any time and using a List of Pair is much better for what I want (and doesn't really work with a Map).

I have this code, but it produces a compiler error

class SnapshotListPairSerializer<K, V>(private val keySerializer: KSerializer<K>, private val valueSerializer: KSerializer<V>) :
    KSerializer<SnapshotStateList<Pair<K, V>>> {
    override val descriptor: SerialDescriptor = ListSerializer(PairSerializer(keySerializer, valueSerializer)).descriptor
    
    override fun serialize(encoder: Encoder, value: SnapshotStateList<Pair<K, V>>) {
        encoder.encodeSerializableValue(ListSerializer(PairSerializer(keySerializer, valueSerializer)), value as List<Pair<K, V>>)
    }
    
    override fun deserialize(decoder: Decoder): SnapshotStateList<Pair<K, V>> {
        val list = mutableStateListOf<Pair<K, V>>()
        val items = decoder.decodeSerializableValue(ListSerializer(PairSerializer(keySerializer, valueSerializer)))
        list.addAll(items)
        return list
    }
}

Also, SnapshotStateList is a class that comes from Jetpack Compose and extends List.


Solution 1:

The exception you get is:

Backend Internal error: Exception during IR lowering

Given that this is not providing you with meaningful information, but mentions compiler internals, this is not an error of your doing, but a bug: a cue to search for known bugs.

This seems very similar to the issue I filed on GitHub.

If it is the same cause, it should be fixed in version 1.6.10. This may explain why Philip can't repro.

P.s. the next problem you will run into is likely that Any is not registered for polymorphic serialization. Serializing Any is dodgy. If you are stuck and the documentation does not help you out, I suggest you post a new question with more information on the exact use case/expected types, and I will gladly help out.