Kotlin:解决通用继承问题

时间:2017-11-21 13:10:03

标签: android kotlin moxy android-moxy

阅读相同的文章后,我仍然无法解决泛型问题:

我有BaseActivity:

abstract class BaseActivity : MvpAppCompatActivity(), BaseView {
    abstract fun getPresenter():BasePresenter<BaseView>
}

它的BaseView接口

interface BaseView : MvpView

肯定是BasePresenter

open class BasePresenter<T : BaseView> : MvpPresenter<T>() 

然后我创建BaseConnectionView

interface BaseConnectionView : BaseView

和BaseConnectionPresenter

class BaseConnectionPresenter<T : BaseConnectionView> : BasePresenter<T>()

所以当我创建BaseConnectionActivity

abstract class BaseConnectionActivity : BaseActivity(),BaseConnectionView {
    override abstract fun getPresenter(): BaseConnectionPresenter<BaseConnectionView>
}

我有错误:

Return type is BaseConnectionPresenter<BaseConnectionView>, 
which is not a subtype of overridden 
public abstract fun getPresenter():BasePresenter<BaseView>

但是它是子类型!

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

BaseConnectionPresenterBasePresenter<T>T: BaseConnectionView的子类型。函数getPresenter仅返回BasePresenter<BaseView>。有一个问题,因为BasePresenter<T>无法保证BasePresenter<BaseView>。以下修复了它:

class BaseConnectionPresenter<T : BaseConnectionView> : BasePresenter<BaseView>()

答案 1 :(得分:0)

如果使用星形投影

,解决方案比我想象的要容易

所以在BaseActivity中我替换了

abstract fun getPresenter():BasePresenter<BaseView>

abstract fun getPresenter():BasePresenter<*>

然后我可以用新的演示者覆盖它,比如

override abstract fun getPresenter(): BaseConnectionPresenter<*>