Kotlin:从方法返回泛型类型?

时间:2021-07-15 20:58:33

标签: java kotlin generics jackson

我有以下一组类:

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)

基本上,我将使用 ApiResponse 类来存储 CustomerUser 的实例,或者通常在 Map<String, Any?> 字段中存储 data 的实例。用这些对象,我写了这个方法:

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
    }

基本上,我的问题是如何使此方法更通用,以便对 CustomerUserMap<String, Any?> 对象使用相同的代码?当我调用此方法时,我会知道预期的返回类型。

1 个答案:

答案 0 :(得分:1)

您正在寻找具体化的类型参数:

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
    }