kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Prefer Contextual serializer of default Polymorphic serializer.

Open AdlerFleurant opened this issue 3 years ago • 3 comments

According to documentation, contextual are preferred over other serializers. However, this was not the case for interfaces.

Polymorphic Serializer was always returned even if a contextual serializer was defined. This change ensures that contextual serializers actually win over other serializers.

Fixes #1645

AdlerFleurant avatar Sep 02 '22 15:09 AdlerFleurant

I'm not sure this is a good idea to change the behavior of a stable function in such a significant way. Also, documentation for SerializersModule.serializer(type: KType) is correct: Attempts to create a serializer for the given [type] and fallbacks to [contextual][SerializersModule.getContextual] lookup for non-serializable types.. Interfaces are always polymorphically serializable, so there's no contradiction.

However, probably specific exceptions for interfaces should be made, if we take into consideration #1207

sandwwraith avatar Sep 07 '22 12:09 sandwwraith

Another problem with preferring contextual (in the absense of a @Contextual annotation is that it would be inconsistent with how serializers are statically resolved (by the plugin) as there will not be a context per definition. As to #1207, the main challenge there is runtime lookup of a serializer that is statically attached to an interface.

pdvrieze avatar Sep 07 '22 18:09 pdvrieze

@sandwwraith and @pdvrieze, I think it makes sense not to prefer contextual serializers. It is still however preferable to use contextual serializers over the default PolymorphicSerializer when a contextual serializer is defined. I will be updating this so that contextual serializers are preferred over the default polymorphicSerializer instead of all serializers.

Would that work?

AdlerFleurant avatar Sep 07 '22 20:09 AdlerFleurant

This is still a big semantic change that can break someone's code, unfortunately. I think you can always specify the serializer explicitly in encodeToString if you want.

sandwwraith avatar Sep 22 '22 15:09 sandwwraith