Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Declarations marked with @Serializable(with=) that have a named companion object fail in serializer(type) on the JVM #2301

Closed
UnderMybrella opened this issue May 12, 2023 · 1 comment

Comments

@UnderMybrella
Copy link

UnderMybrella commented May 12, 2023

Describe the bug
Attempting to retrieve a serializer via serializer(typeOf<SimpleNamedCompanion>()) wrongly declares that SimpleNamedCompanion needs to be marked with Serializable, even though they are.

This does not happen if the default plugin generated serializer is used, or on targets other than the JVM. The Platform check for companion objects for the JVM only checks if there's a declared field named "Companion", which fails if it's named anything else.

To Reproduce
Attach a code snippet or test data if possible.

@Serializable(SimpleNamedCompanion.Named::class)
data class SimpleNamedCompanion(val string: String) {
    companion object Named : KSerializer<SimpleNamedCompanion> {
        override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("SimpleNamedCompanion", PrimitiveKind.STRING)

        override fun deserialize(decoder: Decoder): SimpleNamedCompanion =
            SimpleNamedCompanion(decoder.decodeString())

        override fun serialize(encoder: Encoder, value: SimpleNamedCompanion) {
            encoder.encodeString(value.string)
        }
    }
}

serializer(typeOf<SimpleNamedCompanion>())

I've also attached a test suite at UnderMybrella/KotlinMRE

Expected behavior
The serializer should be retrievable.

Environment

@sandwwraith
Copy link
Member

Duplicate of #1726

Unfortunately it is impossible to understand that named object is a companion using only standard JVM reflection. kotlin-reflect-full is needed for this, but we have to avoid dependency on it in kotlinx-serialization. Therefore, general recommendation is to avoid using named companions in the serializable classes.

Compiler intrinsics (see #1348) solve with this problem when using serializer() with reified type argument instead of KType.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants