generics - 为什么我不能在这个 Rx 转换器中使用接口(interface)作为泛型类型?

标签 generics kotlin rx-java2

我在 Kotlin 中有以下数据类作为引用:

interface GenericResponse {

    val error: Error?

    fun hasErrorObject(): Boolean = error != null
}

data class LoginResponse(
    val name: String,
    val auth: String,
    @SerializedName("error") override val error: Error? = null
) : GenericResponse
LoginResponse实现 GenericResponse .我以下列方式使用 Retrofit API:
@POST("******")
fun createSession(@Body body: LoginBody): Single<Response<LoginResponse>>

此外,我使用转换器从 LoginResponse 中提取错误。如果存在如下图:
class ExceptionTransformers {
    fun <T> wrapRetrofitExceptionSingle(): (Single<Response<T>>) -> Single<T> {
        return { it: Single<Response<T>> ->
            it.flatMap { response: Response<T> ->
                if (response.code() == 200 && response.body() != null) {
                    val genericResponse = response.body() as GenericResponse
                    if (genericResponse.hasErrorObject()) {
                        Single.error { MyException(genericResponse.error!!) }
                    } else {
                        Single.just(response.body()!!)
                    }
                } else {
                    Single.error { UnknownError() }
                }
            }
        }
    }
}

如您所见,我必须将响应正文转换为 GenericResponse实例,然后在 ExceptionTransformer 中继续登录.我的问题是:有没有办法将返回类型用作 GenericResponse而不是输入 T (通用)?我曾尝试这样做 - 但在像这样使用它时遇到了许多错误:
fun createSession(loginBody: LoginBody): Single<LoginResponse> {
    return apiService.createSession(loginBody)
          .compose(exceptionTransformers.wrapRetrofitExceptionSingle())
}

最佳答案

从您指定的内容来看,似乎是 T将始终是 GenericResponse 的子类型- 添加类型参数约束可能是您想要的。

fun <T : GenericResponse> wrapRetrofitExceptionSingle() {
    ...
}

关于generics - 为什么我不能在这个 Rx 转换器中使用接口(interface)作为泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47515612/

相关文章:

由于 Eclipse IDE 导致的 Java 通用问题

java - Java 中的泛型子类型化问题

c# - 使用类型为 DataType 的泛型方法

generics - 接口(interface)之间的 Kotlin 多重继承

kotlin - 为什么具有无限缓冲 channel 的生产者不从 channel 返回或返回无效数据?

android - rxjava2 和 rxkotlin 有什么区别?

android - 将 RxJava Observable 绑定(bind)到 TextView 的文本属性

java - 不兼容的类型 : Single<HttpServer> cannot be converted to Completable

swift - 调用函数时无法推断通用参数 'T'

android - 在Kotlin中将日期时间字符串(2018-04-13T20 :00:00. 0400)转换为日期字符串(April 13, 2018)