In Square’s Retrofit for Android, when you have a GET endpoint which can take a complex combination of parameters, you can use a @QueryMap to pass a map of parameters that will be used for the GET request. Something like this:
interface NewsService {
@GET("/news")
suspend fun getNews(@QueryMap Map<String, String> options): List<News>
}
But what if you want to make sure the endpoint is only called with certain parameters?
To achieve this, we will use of course sealed classes. The kicker comes now though, combining sealed classes and a great but lesser known feature of kotlin, interface delegation, this can be achieved in a simple and powerful form:
interface NewsService {
@GET("/news")
suspend fun getNews(@QueryMap params: QueryParameters): List<News>
}
sealed class NewsSections : Map<String, String> {
object Home : NewsSections(), Map<String, String> by mapOf("page" to "home")
object Breaking : NewsSections(), Map<String, String> by mapOf("page" to "breaking", "count" to "12")
}
Now the endpoint can only be called with certain parameters, which can be defined in an easy to read, yet powerfully concise way.