Kotlin class 泛型类型推断为可为空

Kotlin class generic type infered as nullable

用于保存网络请求结果的通用class

sealed class Result<out T : Any?> {
    data class Success<out T : Any?>(val data: T) : Result<T>()
    data class Error(val message: String, val exception: Exception? = null) : Result<Nothing>()
}

用于将网络结果封装到 Result 中的通用函数。 它从存储库调用并传递一个 retrofit2 api 调用作为输入参数

suspend fun <T: Any?> request(method: Call<T>): Result<T> {
    return withContext(Dispatchers.IO) {
        try {
            val response = method.awaitResponse()   // Retrofit2 Call
            if (response.isSuccessful)
                Result.Success(response.body())
            else
                response.getErrorResult()
        } catch (e: Exception) {
            Result.Error(e.message.orEmpty(), e)
        }
    }
    // Type mismatch.
    // Required: Result<T>
    // Found: Result<T?>
}

是这样叫的

interface Webservice {
    @GET("data")
    fun getData(): Call<Data>   // Retrofit2
}

suspend fun getData(): Result<Data> {
    return request(webservice.getData())
}

为什么将结果推断为类型 T? 而不是 T

问题出在这一行:

Result.Success(response.body())

body is marked with Nullable, so when ported to Kotlin, response.body() returns a T?, rather than T. See here 了解其工作原理。

因此,Result.Success 的类型参数被推断为 T?,因此上面的表达式创建了一个 Result<T?>。注意Result<T?>中的T指的是request的类型参数。