Skip to content

Different behavior of serializer lookup for contextual enum #2569

Open
@shanshin

Description

@shanshin

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]

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions