Hi all, How can one pass a data class as a parame...
# ktor
b
Hi all, How can one pass a data class as a parameter so that ktor-client can return that class type? I can force val result: MyClass = apiclient.post(…) but I want MyClass to be flexible, thanks
a
What do you mean by flexible data class?
b
so I have a func getData(parm1, parm2, CLASS) { … return CLASS apiClient.post() } I can then call getData(xxx, xxx, User::class.java) and getData(yyy, yyy, Score::class.java) when I call getData I can be flexible about the class passed
a
You can use reified type parameter for your function to pass different types of a response body for receiving. Here is an example:
Copy code
suspend fun main(): Unit = coroutineScope {
    val client = HttpClient(CIO) {}
    val response = client.getData<MyClass>("param1", "param2")
}

suspend inline fun <reified T> HttpClient.getData(param1: String, param2: String): T {
    // Use param1 and param2 here
    return post("<https://example.com>")
}

data class MyClass(val x: Int)
🙌 1
b
sweet thanks will do
Thanks Aleksei works great