简体   繁体   中英

How can I encode a typed class with Kotlinx Serialization?

I'd like to encode a given class of type T: EventData with Kotlinx Serialization encodeToString .

This is my code:

class EventDispatcher<T: EventData>(
    val pubSubTemplate: PubSubTemplate
) {
    /**
     * Dispatch an event to the game engine event manager pipeline
     */
    fun dispatchEvent(event: T, initiator: String) {
        val eventData: String = Json.encodeToString(event)
    }

The compiler tells me:

Cannot use `T` as reified type parameter. Use a class instead

Is there a way to make this still work?

For Json.encodeToString(event) to work, it needs the type information for T . But, this type information is lost at runtime due to the way how generics work in Kotlin/Java.

One way to retain the type information would be by making dispatchEvent an inline function with T as a reified type parameter .

However, this also raises the question how you want to serialize event . You could also use polymorphic serialization of EventData , rather than trying to serialize T . This will include an additional class discriminator in your serialized output (it necessarily has to for polymorphic serialization/deserialization to work).

If you serialize the concrete type T , this class discriminator wouldn't be included, which is questionable; how would whoever will deserialize this know what type it is?

In short, I think you need polymorphic serialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM