xref: /aosp_15_r20/external/kotlinx.serialization/guide/example/example-poly-20.kt (revision 57b5a4a64c534cf7f27ac9427ceab07f3d8ed3d8)

<lambda>null1 // This file was automatically generated from polymorphism.md by Knit tool. Do not edit.
2 package example.examplePoly20
3 
4 import kotlinx.serialization.*
5 import kotlinx.serialization.json.*
6 
7 import kotlinx.serialization.descriptors.*
8 import kotlinx.serialization.encoding.*
9 import kotlinx.serialization.modules.*
10 
11 interface Animal {
12 }
13 
14 interface Cat : Animal {
15     val catType: String
16 }
17 
18 interface Dog : Animal {
19     val dogType: String
20 }
21 
22 private class CatImpl : Cat {
23     override val catType: String = "Tabby"
24 }
25 
26 private class DogImpl : Dog {
27     override val dogType: String = "Husky"
28 }
29 
30 object AnimalProvider {
createCatnull31     fun createCat(): Cat = CatImpl()
32     fun createDog(): Dog = DogImpl()
33 }
34 
35 val module = SerializersModule {
36     polymorphicDefaultSerializer(Animal::class) { instance ->
37         @Suppress("UNCHECKED_CAST")
38         when (instance) {
39             is Cat -> CatSerializer as SerializationStrategy<Animal>
40             is Dog -> DogSerializer as SerializationStrategy<Animal>
41             else -> null
42         }
43     }
44 }
45 
46 object CatSerializer : SerializationStrategy<Cat> {
<lambda>null47     override val descriptor = buildClassSerialDescriptor("Cat") {
48         element<String>("catType")
49     }
50 
serializenull51     override fun serialize(encoder: Encoder, value: Cat) {
52         encoder.encodeStructure(descriptor) {
53           encodeStringElement(descriptor, 0, value.catType)
54         }
55     }
56 }
57 
58 object DogSerializer : SerializationStrategy<Dog> {
<lambda>null59   override val descriptor = buildClassSerialDescriptor("Dog") {
60     element<String>("dogType")
61   }
62 
serializenull63   override fun serialize(encoder: Encoder, value: Dog) {
64     encoder.encodeStructure(descriptor) {
65       encodeStringElement(descriptor, 0, value.dogType)
66     }
67   }
68 }
69 
<lambda>null70 val format = Json { serializersModule = module }
71 
mainnull72 fun main() {
73     println(format.encodeToString<Animal>(AnimalProvider.createCat()))
74 }
75