I have a question regarding registering subclasses...
# serialization
a
I have a question regarding registering subclasses of a base class--so I have an abstract class that other response classes extend from and it looks similar to this:
Copy code
@Serializable
abstract class BaseResponseV2<out T>(val success: Success<T>? = null)

@Serializable data class Success<out T>(val data: T? = null)
I usually register subclasses like this:
Copy code
polymorphic(BaseResponseV2::class) {
   subclass(SomeResponse::class)
}
But I forgot to do so for the class below, but didn't encounter any crashes. Based on my understanding of https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#registered-subclasses and previous experiences, I should have gotten errors, but I'm puzzled as to why I didn't receive any for this particular case.
Copy code
@Serializable class GetItemResponse : BaseResponseV2<GetItemResponseData>()

@Serializable
data class GetItemResponseData(val itemName: String? = null)
g
How did you serialize/deserialize?
a
Alvin Dizon [5:48 PM] I use this together with Retrofit:
Copy code
private val serializerModule = SerializersModule {
        polymorphic(BaseResponseV2::class) {
            // subclasses go here
        }
    }    

private val jsonConfig = Json {
        ignoreUnknownKeys = true
        serializersModule = serializerModule
    }

    val serializationFactory =
        JsonConfig.asConverterFactory("application/json".toMediaType())

val retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(BASE_URL)
            .addConverterFactory(serializationFactory)
            .build()
            .create(ItemService::class.java)
g
Can your post also your ItemService class?
a
It should look similar to this:
Copy code
interface ItemService {

    @GET("ItemService/getItem/v1") suspend fun getItem(): GetItemResponse
}
g
I was expecting a GetItemResponseData as the return type to be honest. But as it's reworked code I've some doubts 🙂 (like GetItemResponse is not abstract/open in your example, so there's no polymorphism here...)
a
Hello, so what I'm getting is that
GetItemResponse
does not need to be registered like this:
Copy code
polymorphic(BaseResponseV2::class) {
   subclass(GetItemResponse::class)
}
Even if it is a subclass of BaseResponseV2?