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

Implementation for automatically registering sealed serializers in polymorphic modules #2201

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public class SealedClassSerializer<T : Any>(
}
}

private val class2Serializer: Map<KClass<out T>, KSerializer<out T>>
internal val class2Serializer: Map<KClass<out T>, KSerializer<out T>>
private val serialName2Serializer: Map<String, KSerializer<out T>>

init {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,38 @@ public class PolymorphicModuleBuilder<in Base : Any> @PublishedApi internal cons
private val baseClass: KClass<Base>,
private val baseSerializer: KSerializer<Base>? = null
) {
private val subclasses: MutableList<Pair<KClass<out Base>, KSerializer<out Base>>> = mutableListOf()
private val subclasses: MutableMap<KClass<out Base>, KSerializer<out Base>> = mutableMapOf()
private var defaultSerializerProvider: ((Base) -> SerializationStrategy<Base>?)? = null
private var defaultDeserializerProvider: ((String?) -> DeserializationStrategy<Base>?)? = null


/**
* Registers the child serializers for the sealed [subclass] [serializer] in the resulting module under the [base class][Base].
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documentation here does not mention that Base has to be sealed.

Also, it would be more helpful if documentation contained the example in which scenario this function has to be used. I think #2199 has a good example with

interface Base

@Serializable
sealed interface Sub 

serializersModule {
  polymorphic(Base::class) {
     subclassesOf<Sub>()
  }
}  

*/
public inline fun <reified T : Base> subclassesOf(): Unit =
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All new functions should be marked with @ExperimentalSerializationApi

subclassesOf(serializer<T>())


/**
* Registers the subclasses of the given class as subclasses of the outer class. This currently requires `baseClass`
* to be sealed.
*/
public fun <T: Base> subclassesOf(serializer: KSerializer<T>) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After thinking about it for a while, I came to the idea that subclassesOf is a misleading name. It implies that we can extract all subclasses for an arbitrary class, which we can't do — and as we all know, not every person will be reading documentation to find out that we are able to handle only sealed classes. So more appropriate name would be sealedSubclassesOf or subclassesOfSealed or something in that direction.

require(serializer is SealedClassSerializer) {
"subClassesOf only supports automatic adding of subclasses of sealed types."
}
for ((subsubclass, subserializer) in serializer.class2Serializer.entries) {
@Suppress("UNCHECKED_CAST")
// We don't know the type here, but it matches if correct in the sealed serializer.
subclass(subsubclass as KClass<T>, subserializer as KSerializer<T>)
}
}

/**
* Registers a [subclass] [serializer] in the resulting module under the [base class][Base].
*/
public fun <T : Base> subclass(subclass: KClass<T>, serializer: KSerializer<T>) {
subclasses.add(subclass to serializer)
subclasses[subclass] = serializer
}

/**
Expand Down Expand Up @@ -116,3 +139,9 @@ public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.
*/
public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.subclass(clazz: KClass<T>): Unit =
subclass(clazz, serializer())

/**
* Registers the child serializers for the sealed class [T] in the resulting module under the [base class][Base].
*/
public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.subclassesOf(clazz: KClass<T>): Unit =
subclassesOf(clazz.serializer())
5 changes: 5 additions & 0 deletions docs/polymorphism.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,11 @@ fun main() {

> Note: On Kotlin/Native, you should use `format.encodeToString(PolymorphicSerializer(Project::class), data))` instead due to limited reflection capabilities.

### Registering sealed children as subclasses
A sealed parent interface or class can be used to directly register all its children using `subclassesOf`. This will
expose all children that would be available when serializing the parent directly, but now as sealed. Please note that
this is will remain open serialization, and the sealed parent serializer will not be used in serialization.

<!--- TEST LINES_START -->

### Property of an interface type
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization.features

import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.*
import kotlinx.serialization.test.assertStringFormAndRestored
import kotlin.test.Test

class PolymorphicSealedChildTest {

@Serializable
data class FooHolder(
val someMetadata: Int,
val payload: List<@Polymorphic FooBase>
)

@Serializable
abstract class FooBase

@Serializable
@SerialName("Foo")
sealed class Foo: FooBase() {
@Serializable
@SerialName("Bar")
data class Bar(val bar: Int) : Foo()
@Serializable
@SerialName("Baz")
data class Baz(val baz: String) : Foo()
}

val sealedModule = SerializersModule {
polymorphic(FooBase::class) {
subclassesOf<Foo>()
}
}

val json = Json { serializersModule = sealedModule }

@Test
fun testSaveSealedClassesList() {
assertStringFormAndRestored(
"""{"someMetadata":42,"payload":[
|{"type":"Bar","bar":1},
|{"type":"Baz","baz":"2"}]}""".trimMargin().replace("\n", ""),
FooHolder(42, listOf(Foo.Bar(1), Foo.Baz("2"))),
FooHolder.serializer(),
json,
printResult = true
)
}

@Test
fun testCanSerializeSealedClassPolymorphicallyOnTopLevel() {
assertStringFormAndRestored(
"""{"type":"Bar","bar":1}""",
Foo.Bar(1),
PolymorphicSerializer(FooBase::class),
json
)
}
}