diff options
author | Leonid Startsev <sandwwraith@gmail.com> | 2018-10-30 16:22:58 +0300 |
---|---|---|
committer | Leonid Startsev <sandwwraith@gmail.com> | 2018-10-30 18:03:50 +0300 |
commit | 51d2c562890cd0387283770d6239f4934c6a3bef (patch) | |
tree | 6c4e651a7cce4f2331cf9fb6caf94bf58854241a /docs | |
parent | 9f7e52de8714b13422f4536706821cf67b9f5404 (diff) | |
download | kotlinx.serialization-51d2c562890cd0387283770d6239f4934c6a3bef.tar.gz |
Explicitly add KSerializer supertype to avoid certain restrictions after update
Diffstat (limited to 'docs')
-rw-r--r-- | docs/custom_serializers.md | 7 |
1 files changed, 5 insertions, 2 deletions
diff --git a/docs/custom_serializers.md b/docs/custom_serializers.md index cef1b041..2d956cc8 100644 --- a/docs/custom_serializers.md +++ b/docs/custom_serializers.md @@ -41,7 +41,7 @@ import kotlinx.serialization.internal.* @Serializable class MyData(val s: String) { @Serializer(forClass = MyData::class) - companion object /*: KSerializer<MyData> can be omitted or not, if you like*/{ + companion object : KSerializer<MyData> { override val descriptor: SerialDescriptor = StringDescriptor override fun serialize(output: Encoder, obj: MyData) { @@ -65,7 +65,7 @@ First, we need to correctly fill-in descriptor so all formats would know about m @Serializable class BinaryPayload(val req: ByteArray, val res: ByteArray) { @Serializer(forClass = BinaryPayload::class) - companion object { + companion object : KSerializer<MyData> { override val descriptor: SerialDescriptor = object : SerialClassDescImpl("BinaryPayload") { init { addElement("req") // req will have index 0 @@ -167,6 +167,9 @@ If you're familiar with DI concepts, think of it as _constructor injection_ of s Note that we haven't applied `@Serializable` on the class, because we can't customize it via companion object since companion object can't have constructor arguments. +*Current limitation*: Because primary constructor in such case is generated by the compiler itself, not the plugin, +you have to override `descriptor` manually since it can't be initialized in non-synthetic constructor. + See full sample [here](https://github.com/kotlin/kotlinx.serialization/blob/a4c41392bb735a36788db1d789ec60afdbad3ca8/runtime/jvm/src/test/kotlin/kotlinx/serialization/features/GenericCustomSerializerTest.kt). *Note*: is is broken on JS for now ([#244](https://github.com/Kotlin/kotlinx.serialization/issues/244)). ## Using custom serializers |