1 // This file was automatically generated from polymorphism.md by Knit tool. Do not edit. 2 package example.examplePoly17 3 4 import kotlinx.serialization.* 5 import kotlinx.serialization.json.* 6 7 import kotlinx.serialization.modules.* 8 9 @Serializable 10 abstract class Response<out T> 11 12 @Serializable 13 @SerialName("OkResponse") 14 data class OkResponse<out T>(val data: T) : Response<T>() 15 <lambda>null16val responseModule = SerializersModule { 17 polymorphic(Response::class) { 18 subclass(OkResponse.serializer(PolymorphicSerializer(Any::class))) 19 } 20 } 21 <lambda>null22val projectModule = SerializersModule { 23 fun PolymorphicModuleBuilder<Project>.registerProjectSubclasses() { 24 subclass(OwnedProject::class) 25 } 26 polymorphic(Any::class) { registerProjectSubclasses() } 27 polymorphic(Project::class) { registerProjectSubclasses() } 28 } 29 30 @Serializable 31 abstract class Project { 32 abstract val name: String 33 } 34 35 @Serializable 36 @SerialName("OwnedProject") 37 data class OwnedProject(override val name: String, val owner: String) : Project() 38 <lambda>null39val format = Json { serializersModule = projectModule + responseModule } 40 mainnull41fun main() { 42 // both Response and Project are abstract and their concrete subtypes are being serialized 43 val data: Response<Project> = OkResponse(OwnedProject("kotlinx.serialization", "kotlin")) 44 val string = format.encodeToString(data) 45 println(string) 46 println(format.decodeFromString<Response<Project>>(string)) 47 } 48 49