generics - Kotlin 泛型继承

标签 generics inheritance kotlin type-mismatch

我有一个问题,无法解决。我有一个接口(interface) Presenter这是通用的,采用接口(interface)的任何子类型 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 的错误

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

最佳答案

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

我想说的是您不需要使 BasePresenter 通用。只需将 mvpView 声明为 MvpView 并使用其方法即可。假设如果你确实让它成为通用的,你将不会获得任何加分,因为你仍然只能访问 MvpView 的方法(不是 子类)。

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

希望对您有所帮助。

关于generics - Kotlin 泛型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44213931/

相关文章:

java - 对以前未知元素的列表进行排序 (List<?>)

java - 像这样使用继承是个坏主意吗

Java、继承和实例方法。为什么我的方法不能继承?

android - 如何检查本地 val 是否已初始化?

java - 泛型:为什么 Class<Integer[]> clazzIntArray = int[].class;不起作用

具有不同类型的 Swift Codable

c# - 转换为实现接口(interface)的通用抽象类

ruby-on-rails - 单表继承以及在 Rails 中使用它的位置

android - 如何在 Kotlin 中定义返回 RadioButton 当前值的属性?

Kotlin的逻辑 'and'没有短路?