This could be more a JVM ecosystem question than K...
# getting-started
l
This could be more a JVM ecosystem question than Kotlin specifically… I have this code:
Copy code
val body = objectMapper.writeValueAsString(error)
val request = HttpEntity<String>(body, headers)
restTemplate.exchange(uri, HttpMethod.POST, request)
I just want to send a postback message to an endpoint. I do not care about the response at all. However, RestTemplate.exchange() insists on a 4th argument that is the class name to cast the response into. Is there an alternate approach for when I don’t know or care what comes back, I just want to send-and-forget? (This is in SpringBoot, but I’m not sure if that matters. Still new to the ecosystem and not sure where the lines are.)
y
I mean if you pass in the class
Any
(or
Object
in Java) then it should always succeed
l
Hm.
Copy code
restTemplate.exchange(uri, <http://HttpMethod.POST|HttpMethod.POST>, request, Any::class.java)
That at least keeps my IDE happy. I feel like I’m probably not doing this optimally, but I guess it works?
y
That's the right way to do it I'd say. You could define an extension method to do this for you:
Copy code
fun RestTemplate.exchangeAndForget(uri: Uri, method: HttpMethod, request: HttpEntity) {
  exchange(uri, method, request, Any::class.java)
}
Or you could go the extra mile and create a nicer
exchange
method using Kotlin's
reified
types:
Copy code
inline fun <reified T> RestTemplate.exchange(uri: Uri, method: HttpMethod, request: HttpEntity): T =
  exchange(uri, method, request, T::class.java)
and then when you don't care about the result you can simply do
restTemplate.exchange<Any?>(uri, <http://HttpMethod.POST|HttpMethod.POST>, request)
, and when you care about the result, then you can use the right type
r
Kotlin extension methods for RestTemplate are already present in the spring-web library. The Kotlinified
exchange
method that @Youssef Shoaib [MOD] mentioned above is available, see: https://github.com/spring-projects/spring-framework/blob/93387e69b53620b13b379bd972a18cdc3fd54be7/spring-web/src/main/kotlin/org/springframework/web/client/RestOperationsExtensions.kt#L275 Which means you could already write it as follows, as long as you (let IntelliJ) add the necessary import:
Copy code
import org.springframework.web.client.exchange

// ...

restTemplate.exchange<Any?>(uri, HttpMethod.POST, request)
❤️ 1
l
Huh. OK then. It’s not worth building my own extension wrapper for this use case, but if Spring already has one, I’ll just use that. Thanks.