Tech
09/01/2022, 12:07 PMNothing
to a reified type, or something similar?Gleb Minaev
09/01/2022, 12:26 PMNothing
) cannot be used as an argument for a reified type parameter.
©️ Kotlin docsTech
09/01/2022, 12:31 PMGleb Minaev
09/01/2022, 12:42 PMNothing
)).Tech
09/01/2022, 1:32 PMTech
09/01/2022, 1:35 PMServiceResponse.Success
or ServiceResponse.Failure
, they just represent whether the request to the API was successful or if an error occurred.
I pass a generic to these to define a property called data
in each of them and whenever I don't expect any data back from the API I just pass Nothing
, so an example of what I do is this.
ServiceResponse.Failure<Nothing>()
So I have another function that I use to send this Http request to the API then I use kotlinx serialization to decode the returned JSON and do whatever I need to on that.Tech
09/01/2022, 1:36 PMprotected suspend inline fun <reified T, reified B> bodiedRequestWithResponse(
request: ServiceRequest<B>
) : ServiceResponse<T> {
val (endpoint, type, body) = request
val con = establishConnection(endpoint, type)
?: return ServiceResponse.Failure<Nothing>("connection failed.")
return JSON.decodeFromString(con.attachBodyAndDecode(body))
}
Tech
09/01/2022, 1:37 PMattachBodyAndDecode
takes the custom body I pass to the request and puts it onto the request then I decode that string retrieved.
But if I don't expect any data back I can't use Nothing
because it's an invalid reified type.Tech
09/01/2022, 1:39 PMprotected suspend inline fun request(
request: ServiceRequest<Nothing>
) : ServiceResponse<Nothing> {
val (endpoint, type) = request
val con = establishConnection(endpoint, type)
?: return ServiceResponse.Failure("connection failed.")
return JSON.decodeFromString(con.decodeStream())
}
protected suspend inline fun <reified T> requestWithResponse(
request: ServiceRequest<Nothing>
) : ServiceResponse<T> {
val (endpoint, type) = request
val con = establishConnection(endpoint, type)
?: return ServiceResponse.Failure<Nothing>("connection failed.")
return JSON.decodeFromString(con.decodeStream())
}
Tech
09/01/2022, 1:39 PMGleb Minaev
09/01/2022, 1:56 PMUnit
instead of Nothing
. Because it's more idiomatic. While Unit
represents "no return/output" ("it just did some work and there is no output of the work"), Nothing
represents "just nothing". Nothing
(shortly saying) means that you won't get the result by some reason. I.e. fun foo(): Unit
means that there will be result but no output, whereas fun bar(): Nothing
means that there even won't be any result of the execution. It's also confirmed by fact that the sources of all `Nothing`s are throw
and (empty) return
expressions.
Also, Unit
is reifiable.Tech
09/01/2022, 2:08 PMTech
09/01/2022, 2:09 PMephemient
09/01/2022, 4:31 PMNothing
is equivalent to Never
in Swift and Rust (which also has the shortcut !
), if that name helps