I am trying to create a generic http client class ...
# ktor
j
I am trying to create a generic http client class with ktor and in my class I declare the HttpClient like this
Copy code
private val _client: HttpClient = HttpClient {
    install(ContentNegotiation) {
        json(Json {
            this.isLenient = true
            this.ignoreUnknownKeys = true
        })
    }
}
and an example generic method I am trying to create is like this
Copy code
suspend inline fun <reified T> get(builder: HttpRequestBuilder): T? {
    val response = _client.get(builder)

    ....

    return response.body()
}
Where when using this method you give the type the response should be (deserialized to an object from json). The IDE is telling me
Public-API inline function cannot access non-public-API
on the
client
object, I dont want that public to be used outside of this class so what are my options here
p
You can make the _client
internal
and add the
@PublishedApi
annotation to allow it to be used from within a public inline method
j
That makes client available outside of that class though, I need it so that no other class can access it
p
You can make a public non-inline method that takes the typeinfo as a parameter that's ultimately passed in the .body() call.
1
j
so it would be like this?
Copy code
suspend fun <T> get(builder: HttpRequestBuilder, typeInfo: TypeInfo): T? {
    val response = _client.get(builder)

    ....

    return response.body(typeInfo)
}
Copy code
myHttpClient.get<TestData>(builder, typeInfo<TestData>())
p
Yes but that latter statement could be in an inline reified method to make normal call-sites simpler
Copy code
suspend inline fun <reified T> get(builder: HttpRequestBuilder): T? = get(builder, typeInfo<T>())
1