Hello, How can I compare generic class with list c...
# announcements
p
Hello, How can I compare generic class with list class? I have a generic class named BaseResponse now I want to extract the actual type "O" from the base-response. I have used the inline function with reified type parameter as defined in kotlin documentation but it is not working. This is my function in which I am passing the base response model and comparing the java class and getting the actual object. But If there is a List type like BaseResponseModel<List> it is always going in the else branch, not in the first comparison of the when statement.
Copy code
inline fun <reified O> getAPIResult(apiResponse: BaseResponseModel<O>): O? {
    val actualResult: O? = try {
        when (O::class.java) {
            List::class.java -> {
                apiResponse.getResponseModel(object : TypeToken<List<O>>() {}.type)
            }
            ArrayList::class.java -> {
                apiResponse.getResponseModel(object : TypeToken<ArrayList<O>>() {}.type)
            }
            else -> {
                apiResponse.getResponseModel(O::class.java)
            }
        }
    } catch (e: Exception) {
        null
    }
    return actualResult
}
m
How are you calling this. The type of
0
is still going to be resolved at compile time and not runtime, so if you are calling it with
O
being
Any
it will go to the else. Since it is all resolved at compile time, it would make more sense to just have three different methods. The last case makes some sense to be inline with reified types.
Also are you doing the correct type token. If
O
is a
List
, you will be doing something like
TypeToken<List<List<*>>()
☝️ 1
p
So basically I am calling this from another inline function.
Copy code
inline fun <reified O> fetchDataFromAPI(
    crossinline apiMethod: suspend () -> BaseResponseModel<O>
): Flow<APIResult<O>> {
    return flow {
        emit(APIResult.loading<O>())
        if (Utils.isNetworkAvailable()) {
            try {
                val response = apiMethod.invoke()
                emit(getAPIResult(response))
            } catch (e: Exception) {
                APIResult.error(null, e.message ?: "")
            }
        } else {
            emit(APIResult.noNetwork<O>())
        }
    }.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
}
And the API method I am passing is to this inline function is like this, it is a retrofit interface method.
suspend fun getAllCity() : List<City>
So is there any solution to this problem?