I'm running into some issues with generic or polym...
# serialization
g
I'm running into some issues with generic or polymorphic types:
Copy code
@Serializable
data class Folder(
    val content: SingleOrCollection<File>
)

@Serializable
data class File(val name: String)

@Serializable
sealed class SingleOrCollection<T> {

    @Serializable
    @SerialName("single")
    class Single<T>(val data: T) : SingleOrCollection<T>()

    @Serializable
    @SerialName("collection")
    class Collection<T>(val data: List<T>) : SingleOrCollection<T>()

}
I get a an exception when trying to serialize 
Folder(SingleOrCollection.Single(File(fileName)))
with
json.encodeToString(folder)
Copy code
kotlinx.serialization.SerializationException: Class 'File' is not registered for polymorphic serialization in the scope of 'Any'.
Mark the base class as 'sealed' or register the serializer explicitly.
It seems looks like a pretty simple use case. Does anyone know what the issue could be?
p
Both
Collection
and
Single
are containers of polymorphic values. The base type is unconstrained (erasure) thus
Any
. As such you need to create a
serializersModule
that registers
File
as a valid subtype for
Any
.
g
Both 
Collection
 and 
Single
 are containers of polymorphic values
How so? Can you explain this further?
p
Basically, they contain a value (values) of a type that at compilation time cannot be determined. That means that polymorphic serialization is needed. Normally, serialization would use a parameter to the serializer to specify a child that is specified. I suspect that the interaction with sealed classes means that this isn't done (put a but into the issue tracker): https://github.com/Kotlin/kotlinx.serialization/issues
Note that serialization of sealed classes is basically polymorphic serialization but without the need for direct registration in a serializersModule.
g
Cool, thanks 👍 I'll try to work around this because in my use case I can't define all the types that the generic might have under the serializersModule.