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

Different behavior of serializer lookup for contextual enum

Open shanshin opened this issue 1 year ago • 0 comments

The following types are given:

object PlainSerializer: ToDoSerializer<Plain>("my-plain")
object EnumSerializer: ToDoSerializer<EnumType>("my-enum")

class Plain(val i: Int)
enum class EnumType { A, B }
...
abstract class ToDoSerializer<T: Any>(descriptorName: String): KSerializer<T> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor(descriptorName, PrimitiveKind.STRING)
    override fun deserialize(decoder: Decoder): T = TODO()
    override fun serialize(encoder: Encoder, value: T) = TODO()
}

if you specify the serialization module:

    val module = SerializersModule {
        contextual(PlainSerializer)
        contextual(EnumSerializer)
    }

Serializer lookup

    println("serializer<...>()")
    println(module.serializer<Plain>().descriptor.serialName)
    println(module.serializer<EnumType>().descriptor.serialName)
    println()
    println("serializer(typeOf<...>())")
    println(module.serializer(typeOf<Plain>()).descriptor.serialName)
    println(module.serializer(typeOf<EnumType>()).descriptor.serialName)

Will print

serializer<...>()
my-plain
EnumType

serializer(typeOf<...>())
my-plain
EnumType

This behavior does not change even if you specify @file:UseContextualSerialization(Plain::class, EnumType::class)

Expected behavior It is necessary to make a decision, if @file:UseContextualSerialization(EnumType::class) is specified, whether to throw a compilation error (add an inspection), or change behaviour of lookup contextual enum.

Environment

  • Kotlin version: 1.9.22
  • Library version: 1.6.1
  • Kotlin platforms: JVM
  • Gradle version: [e.g. 4.10]

shanshin avatar Feb 13 '24 16:02 shanshin