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

Access the autogenerated serializer for a enum class

Open dkhalanskyjb opened this issue 4 years ago • 2 comments

Currently, there is no simple way to access the serializer that is generated for a enum class. For first-party code, there is a workaround (that is seemingly undocumented or at least obscure): annotate the enum class with @Serializable and explicitly call MyEnum.serializer(). For third-party code, where it's impossible to add @Serializable, a clunkier workaround is needed:

@ExperimentalSerializationApi
@Serializer(forClass = MyEnum::class)
object MyEnumSerializer

This way, another serializer is generated that can be accessed, but generating another serializer just to be able to access it seems odd.

Since the serializer does exist in some form, maybe there should be some simpler means to access it.

What is your use-case and why do you need this feature?

There are many use cases for wanting to explicitly pass a serializer around.

Describe the solution you'd like

The best quality of life for the end programmers would probably be achieved by emulating the existence of a .serializer() method on the companion objects of enum classes, but, really, any way to access the generated serializer would do.

dkhalanskyjb avatar Nov 30 '20 09:11 dkhalanskyjb

See also: #1169

sandwwraith avatar Dec 01 '20 10:12 sandwwraith

Is there also a way to make this work with contextual serialization, so that in some contexts I could refer to the autogenerated serializer for an enum class?

sschuberth avatar Mar 03 '22 12:03 sschuberth

Closed as a buplicate of https://github.com/Kotlin/kotlinx.serialization/issues/1169

shanshin avatar Nov 01 '23 16:11 shanshin