Can Retrofit convert @Path parameters from custom class to primitive types

Viewed 289

I have a following Retrofit request:

@GET("event/{id}")
suspend fun getEvent(@Path("id") eventId: Long): Response<Event>

However in my application I'm using the following wrapper for the event id:

data class EventId(val value: Long)

Is it possible to pass EventId class as a path parameter and somehow tell Retrofit how to convert the value to Long? Here is the method signature I want to have:

@GET("event/{id}")
suspend fun getEvent(@Path("id") eventId: EventId): Response<Event>
1 Answers

The solution I've found is to register converter factory in the Retrofit Builder:

class EventIdConverterFactory : Converter.Factory() {
    override fun stringConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit) =
        if (type == EventId::class.java) {
            Converter<Any, String> { (it as EventId).value.toString() }
        } else {
            super.stringConverter(type, annotations, retrofit)
        }
}
Related