I have a sealed class which represents the Retrofit Response of my API.
sealed class NetworkResponse<out T : Any, out U : Any> {
data class Success<T : Any>(val body: T) : NetworkResponse<T, Nothing>()
data class ApiError<U : Any>(val body: U, val code: Int) : NetworkResponse<Nothing, U>()
data class NetworkError(val error: IOException) : NetworkResponse<Nothing, Nothing>()
data class UnknownError(val error: Throwable?) : NetworkResponse<Nothing, Nothing>()
}
So now i want to create a function that handles all the errors of a failed request. I want to have only one argument that represents either ApiError or NetworkError or UnknownError
fun networkErrorHanlder(mError: <what_should_i_put_here??>) {
// check if error is Api or Network or Unknown and do stuff...
}
What should be the type of the argument?
Since you care only about ApiError
, NetworkError
and UnknownError
, which all derive from NetworkResponse
but don't use the first generic type, you can specify that you don't care about it using *
(Actually, depending on what you want to do with mError
, you can replace U
with *
too - that is the case in the code below, but I introduced U
just in case). In that case, you should accept a NetworkReponse
:
fun <U : Any> networkErrorHanlder(mError: NetworkResponse<*, U>) {
when(mError) {
is NetworkResponse.ApiError ->
print("Api stuff: ${mError.body}")
is NetworkResponse.NetworkError ->
print ("Network stuff: ${mError.error}")
is NetworkResponse.UnknownError ->
print("Unknown: ${mError.error}")
else -> print("It must've been a Success...")
}
}