Hi guys, I’m struggling with a piece of code while...
# coroutines
c
Hi guys, I’m struggling with a piece of code while trying to use coroutines. I’m calling Spring’s
reactive.function.client
method
awaitBody()
from a Generic class and am running into error:
Copy code
Kotlin: Cannot use 'Response' as reified type parameter. Use a class instead.
---
Copy code
class ReactiveWebClient<Request: Any, Response: Any> {

    suspend fun post(uri: URI, request: Request, headers: (HttpHeaders) -> Unit): Response {
        return <http://webClient.post|webClient.post>()
            .uri(uri)
            .body(BodyInserters.fromValue(request))
            .headers(headers)
            .retrieve()
            .awaitBody()  // error on this line
    }
}
Signature of `awaitBody`:
Copy code
public suspend inline fun <reified T : kotlin.Any> org.springframework.web.reactive.function.client.WebClient.ResponseSpec.awaitBody(): T { /* compiled code */ }
Can someone please help? I’m not so well versed with Kotlin’s type parameters.
d
During compilation kotlin wants to inline the call
awaitBody
but at the call site (inside your class) the type is not known at compilation time (due to type erasure) I'm actually not sure how you solve this. How about extracting
post
into an extension method that uses a reified type parameter and can be inlined? The webClient you're wrapping could be the target?
u
Maybe this works. haven’t tried:
Copy code
class ReactiveWebClient<Request: Any, Response: Any> {
    suspend inline fun <reified T: Response> post(uri: URI, request: Request, headers: (HttpHeaders) -> Unit): T
Do you really need Resonse as a type parameter to the class? Otherwise remove it and make it a type parameter of the fun:
Copy code
suspend inline fun <reified Response: Any> post(uri: URI, request: Request, headers: (HttpHeaders) -> Unit): Response
c
Thanks Dennis and Uli, I went ahead with Dennis’s advice and converted the class into an extension function. Now it looks something like this: PS: awaitBody was still not working. Copy pasting this from awaitBody ’s implementation bodyToMonoResponse().awaitSingle() made it work.
🎉 1