Kotlin / kotlinx.serialization

Kotlin multiplatform / multi-format serialization
Apache License 2.0
5.33k stars 618 forks source link

[FEATURE] Allow defining a sealed class as a subclass of an open polymorphic class #2782

Open rocketraman opened 1 month ago

rocketraman commented 1 month ago

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

I have an open interface, say MyOpenInterface.

I have an implementation of this open interface which is sealed i.e. sealed class MySealed: MyOpenInterface { ... }.

Currently, it seems the only way to define the SerializersModule is to explicitly list all the subtypes of the sealed class:

polymorphic(MyOpenInterface::class) {
  subclass(MySealedSub1::class)
  subclass(MySealedSub2::class)
  ...
}

This was raised on Slack, but no alternative options were provided by anyone.

Describe the solution you'd like

I would like to define a SerializersModule as follows, which would make the module type-safe:

polymorphic(MyOpenInterface::class) {
  subclass(MySealed::class)
}

At the moment, attempting to do this results in an error like this:

Serializer for MySealed can't be registered as a subclass for polymorphic serialization because its kind SEALED is not concrete. To work with multiple hierarchies, register it as a base class.
pdvrieze commented 1 month ago

Would this match pull request #2201 ? I could try to refresh/rebase the pull request.

rocketraman commented 1 month ago

Would this match pull request #2201 ? I could try to refresh/rebase the pull request.

@pdvrieze Yes, I believe it would.