【问题标题】:Using subclasses with RxJava Observable使用带有 RxJava Observable 的子类
【发布时间】:2019-03-25 09:30:53
【问题描述】:

我遇到以下代码错误:

interface A1 {
    val string: String
}

data class A2(override var string: String = "") : A1

interface Test {
    fun f(): Observable<List<A1>>
}

fun func(): Observable<List<A2>> = return ...

class TestImpl : Test{
    override fun f(): Observable<List<A1>> = func()
}

最后一行代码中存在类型不匹配。如果可能的话,我该如何更改它以获得正确的声明?

【问题讨论】:

    标签: android generics kotlin rx-java


    【解决方案1】:

    您可以按如下方式通用化您的界面:

    interface Test<T: A1> {
        fun f(): Observable<List<T>>
    }
    

    然后实现如下:

    class TestImpl : Test<A2> {
        override fun f(): Observable<List<A2>> = func()
    }
    

    【讨论】:

    • 我试过out List,但还是不行。我收到的out 警告是projection is redundant the corresponding type parameter of list has the same variance
    • 但如果我确实使用List 而不是MutableList,并删除Observable,它就可以工作。实际上,List 就是我所需要的,因为我只需要读取这些值。我会更新问题以反映这一点。尽管如此,Observable 仍然需要,问题仍然存在。
    • 已更改我的答案以适应更新后的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2018-04-10
    • 2018-11-29
    相关资源
    最近更新 更多