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

Automatically serialize non-@Serializable inline classes when used as properties

Open rnett opened this issue 1 year ago • 1 comments

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

I'm using Compose, which defines quite a few inline classes (aka single-value value classes), for example Dp, which is defined as @kotlin.jvm.JvmInline value class Dp(val value: Float)). None of these classes are serializable out of the box, which is quite annoying since there are a lot of them, and they show up a lot when trying to save UI state. While you can define custom serializers for them and use them via typealises or contextual serializers, that still ends up being a lot of boilerplate.

Describe the solution you'd like

These inline classes are trivially serializable as the type they wrap. This is what the generated serializer does. I would like for generated serializers of classes with inline class properties to do this automatically if the property types do not have serializers defined.

rnett avatar Mar 16 '24 20:03 rnett

It's not as easy as it sounds. While properties of value types are indeed stored as their carrier type, there are cases when they are stored as boxes. For example, in @Serializable class X(val list: List<Dp>), list contains instances of Dp, not Float. Therefore, we need to have a serializer for Dp anyway. And it can't be generic FloatValueClassSerializer, because different value classes can have different carrier property names. In theory, such serializer can be generated on use-site. But I'd rather avoid that, as 1) we don't want to assume that the user meant this type to be implicitly serializable; 2) it will lead to a large amount of duplicated identical classes.

sandwwraith avatar Mar 18 '24 13:03 sandwwraith