HelloWorld
HelloWorld

Reputation: 171

Kotlin: Return generic types from a method?

I have the following set of classes:

data class ApiResponse<T>(val httpCode: String? = null, val data: T? = null, val status: String? = null, val error: String? = null)

data class Customer(val name: String? = null)

data class User(val userId: String = "", val name: String? = null, val description: String? = null)

Basically, I will use the ApiResponse class to store an instance of Customer or User or sometimes a Map<String, Any?> in the data field generically. With these objects, I wrote this method:

private fun handleError(errorJson: String?): ApiResponse<Customer> {
        var response: ApiResponse<Customer>
            try {
                response = objectMapper.readValue(errorJson, object: TypeReference<ApiResponse<Customer>>(){})
            } catch (ex: Exception) {
                // unable to parse
                response = ApiResponse(
                        status = "500",
                        error = "Unknown error"
                )
            }
        
        return response
    }

Basically, my question is how do I make this method more generic so the same code can be used for both Customer,User, Map<String, Any?> objects? I would know when I am invoking this method the expected return type.

Upvotes: 0

Views: 276

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198133

You're looking for reified type parameters:

private inline fun <reified T> handleError(errorJson: String?): ApiResponse<T> {
        var response: ApiResponse<Customer>
            try {
                response = objectMapper.readValue(errorJson, object: TypeReference<ApiResponse<T>>(){})
            } catch (ex: Exception) {
                // unable to parse
                response = ApiResponse(
                        status = "500",
                        error = "Unknown error"
                )
            }
        
        return response
    }

Upvotes: 1

Related Questions