简体   繁体   English

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

[英]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.基本上,我将使用ApiResponse类在data字段中存储CustomerUser的实例,有时也存储Map<String, Any?> 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?基本上,我的问题是如何使此方法更通用,以便相同的代码可用于CustomerUserMap<String, Any?>对象? I would know when I am invoking this method the expected return type.当我调用此方法时,我会知道预期的返回类型。

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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM