I’m following along with <https://github.com/Kotli...
# serialization
l
I’m following along with https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#objects and I found that the list of multiple objects caused the type to show up, but if I only had EmptyResponse, then the output would just be [{}]. Is there a way to force it to give the type when there’s only one object?
A list of two EmptyResponse gave [{}, {}], but if I made a second object and used both, it would give the types.
d
Code snippet? I'm 99.99% sure I know what's wrong.
e
yep. symptom sounds you're calling the serializer with the wrong reified type.
l
I’m calling
Json.encodeToString(listOf(EmptyResponse, EmptyResponse))
. This is currently only for encoding. I’m not decoding it yet.
d
Json.encodeToString(listOf<BaseClass>(EmptyResponse, EmptyResponse))
l
Same result with
Json.encodeToString(EmptyResponse)
I’ll look at that.
d
Json.encodeToString<BaseClass>(EmptyResponse)
l
That works.
e
also
Copy code
val list: List<BaseClass> = listOf(EmptyResponse)
Json.encodeToString(list)
and all sorts of other variations
l
Interesting. Why does it require that I explicitly mark it as Response?
e
because Kotlin infers the narrowest possible type for
listOf(EmptyResponse)
unless it has another reason to, which is
List<EmptyResponse>
, which is not polymorphic
I would tend to avoid the reified helper functions in kotlinx.serialization anyway, due to the need for reflection to obtain the serializer (waiting on https://github.com/Kotlin/kotlinx.serialization/issues/1348)
l
That makes sense. I guess I’ll have to be careful when I work with polymorphic serializers. I noticed that even when I used a serializerModule, it would still happen. I would have assumed that the fact that I marked EmptyClass as a subclass would tell it to use polymorphism.
e
no, EmptyClass is only polymorphic in the context of a BaseClass
you can register a class as belonging to multiple polymorphic hierarchies
☝🏼 1
l
That makes sense.