From 1aead700f6376ccfbaad37b8e2ad85bddd6ea95f Mon Sep 17 00:00:00 2001 From: Paul de Vrieze Date: Mon, 20 Feb 2023 18:58:32 +0000 Subject: [PATCH] Tidy up the code a bit (and use the cast method on the serializer to avoid casting warnings). Use a map to allow faster lookup of serializers to class (to allow for overlapping hierarchies). --- .../modules/PolymorphicModuleBuilder.kt | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/core/commonMain/src/kotlinx/serialization/modules/PolymorphicModuleBuilder.kt b/core/commonMain/src/kotlinx/serialization/modules/PolymorphicModuleBuilder.kt index befafbe2a..41b27af03 100644 --- a/core/commonMain/src/kotlinx/serialization/modules/PolymorphicModuleBuilder.kt +++ b/core/commonMain/src/kotlinx/serialization/modules/PolymorphicModuleBuilder.kt @@ -19,7 +19,7 @@ public class PolymorphicModuleBuilder @PublishedApi internal cons private val baseClass: KClass, private val baseSerializer: KSerializer? = null ) { - private val subclasses: MutableList, KSerializer>> = mutableListOf() + private val subclasses: MutableMap, KSerializer> = mutableMapOf() private var defaultSerializerProvider: ((Base) -> SerializationStrategy?)? = null private var defaultDeserializerProvider: ((String?) -> DeserializationStrategy?)? = null @@ -29,13 +29,14 @@ public class PolymorphicModuleBuilder @PublishedApi internal cons public fun subclass(subclass: KClass, serializer: KSerializer) { if (serializer is SealedClassSerializer) { - for ((subsubclass, subserializer) in serializer.class2Serializer.entries) { - @Suppress("UNCHECKED_CAST") - // We don't know the type here, but it matches if correct in the sealed serializer. - subclass(subsubclass as KClass, subserializer as KSerializer) + for ((subsubclass, subserializer) in serializer.class2Serializer) { + // Allow for overlapping hierarchies (possible with sealed interfaces) + if (subsubclass !in subclasses) { + subclass(subsubclass, subserializer.cast()) + } } } else { - subclasses.add(subclass to serializer) + subclasses.put(subclass, serializer) } }