Skip to content

Commit

Permalink
Tidy up the code a bit (and use the cast method on the serializer to …
Browse files Browse the repository at this point in the history
…avoid casting warnings). Use a map to allow faster lookup of serializers to class (to allow for overlapping hierarchies).
  • Loading branch information
pdvrieze committed Mar 16, 2023
1 parent 28c8fcd commit 1aead70
Showing 1 changed file with 7 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class PolymorphicModuleBuilder<in Base : Any> @PublishedApi internal cons
private val baseClass: KClass<Base>,
private val baseSerializer: KSerializer<Base>? = null
) {
private val subclasses: MutableList<Pair<KClass<out Base>, KSerializer<out Base>>> = mutableListOf()
private val subclasses: MutableMap<KClass<out Base>, KSerializer<out Base>> = mutableMapOf()
private var defaultSerializerProvider: ((Base) -> SerializationStrategy<Base>?)? = null
private var defaultDeserializerProvider: ((String?) -> DeserializationStrategy<Base>?)? = null

Expand All @@ -29,13 +29,14 @@ public class PolymorphicModuleBuilder<in Base : Any> @PublishedApi internal cons
public fun <T : Base> subclass(subclass: KClass<T>, serializer: KSerializer<T>) {

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<T>, subserializer as KSerializer<T>)
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)
}
}

Expand Down

0 comments on commit 1aead70

Please sign in to comment.