如何使用嵌套泛型编写扩展功能?

时间:2019-06-19 07:32:00

标签: generics kotlin kotlin-android-extensions

我在Single类上具有扩展功能:

fun <T: Response<BaseResponse>> Single<T>.checkResponse(): Single<BaseResponse> {
    return this.map { some code }
}

并尝试像这样使用它:

fun sign(body: Map<String, String>): Single<SignResponse> {
    return service.sign(body).checkResponse().map { it }
}

服务的签名:

@POST(Urls.SIGN)
fun sign(@Body body: Map<String, String>): Single<Response<SignResponse>>

SignResponse明显继承了BaseResponse

响应是retrofit2.response

我有一个错误:

Type parameter bound for T in fun <T : Response<BaseResponse>> Single<T>.checkResponse(): Single<BaseResponse> is not satisfied: inferred type Response<SignResponse> is not a subtype of Response<BaseResponse>

我需要如何编写扩展功能来告诉编译器Single具有Response,其类型继承自BaseResponse

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

fun <R: BaseResponse, T: Response<R>> Single<T>.checkResponse(): Single<R>