Thread
#serialization
    gsala

    gsala

    1 year ago
    I'm running into some issues with generic or polymorphic types:
    @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)
    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

    pdvrieze

    1 year ago
    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
    .
    gsala

    gsala

    1 year ago
    Both 
    Collection
     and 
    Single
     are containers of polymorphic values
    How so? Can you explain this further?
    p

    pdvrieze

    1 year ago
    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.
    gsala

    gsala

    1 year ago
    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.