https://kotlinlang.org logo
Title
b

Barry Fawthrop

03/04/2022, 7:11 PM
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

Aleksei Tirman [JB]

03/05/2022, 8:22 AM
What do you mean by flexible data class?
b

Barry Fawthrop

03/05/2022, 3:56 PM
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

Aleksei Tirman [JB]

03/05/2022, 5:41 PM
You can use reified type parameter for your function to pass different types of a response body for receiving. Here is an example:
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

Barry Fawthrop

03/06/2022, 3:52 PM
sweet thanks will do
Thanks Aleksei works great