【问题标题】:How to write extension function with nested generics?如何使用嵌套泛型编写扩展函数?
【发布时间】:2019-06-19 07:32:00
【问题描述】:

我在 Single class 上有扩展功能:

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 }
}

服务的sign签名:

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

SignResponse 显然继承了 BaseResponse

响应是 retrofit2.response

我有一个错误:

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

如何编写扩展函数来告诉编译器 Single 有 Response,其类型继承自 BaseResponse?

【问题讨论】:

    标签: generics kotlin kotlin-extension


    【解决方案1】:

    你可以试试这样的:

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

    【讨论】:

    • 谢谢!我以为我尝试了类似的方法,但显然我在某个地方犯了错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2023-01-10
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多