Kotlin通用继承

时间:2017-05-27 06:55:28

标签: generics inheritance kotlin type-mismatch

我遇到了问题,无法解决问题。我有一个接口Presenter,它是通用的,接受任何接口MvpView

的子类型
interface Presenter<in V : MvpView> {
    fun attachView(view: V)
    fun detachView()
}

然后我有另一个  抽象类BasePresenter,它是Presenter

的子类型
abstract class BasePresenter<V : MvpView> : Presenter<V> {

    protected var mvpView: V? = null
        protected get

    override fun attachView(view: V) {
        this.mvpView = view
    }

    override fun detachView() {
        mvpView = null
    }
}

我有一个班级

abstract class BaseMvpActivity<P : BasePresenter<T>, T : MvpView> : BaseActivity(), MvpView {

    @Inject lateinit protected var presenter: P

    protected abstract fun inject()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        inject()
        initPresenter(savedInstanceState)
    }

    protected fun initPresenter(savedInstanceState: Bundle?) {
        presenter.attachView(this)
    }

    override fun onDestroy() {
        presenter.detachView()
        super.onDestroy()
    }
}

尝试拨打presenter.attachView(this)

时出现错误
Type mismatch: inferred type is BaseMvpActivity<P, T> but T was expected

我也尝试这样做abstract class BaseMvpActivity<P : BasePresenter<*>> : BaseActivity(),但也有像Type mismatch: inferred type is BaseMvpActivity<P> but Nothing was expected

这样的错误

我该如何解决这个问题?谢谢。

1 个答案:

答案 0 :(得分:-1)

为什么要使BasePresetner通用,因为您不会返回该泛型类型的值。我们使用泛型来防止从方法返回值的类型转换,并防止可能的Cast异常。

我想说的是你不需要BasePresenter通用。只需将mvpView声明为MvpView并使用其方法即可。假设你确实使它成为通用的,那么你将无法获得加分,因为你仍然只能访问MvpView的方法(不是sub-class)。

abstract class BasePresenter : Presenter<V> {

    protected var mvpView: MvpView = null
        protected get

    override fun attachView(view: MvpView) {
        this.mvpView = view
    }

    override fun detachView() {
        mvpView = null
    }
}

希望它有所帮助。