我尝试将以下Java类转换为使用泛型的Kotlin。

抽象类MvpViewHolder,M,V:视图?>(itemView:视图):RecyclerView.ViewHolder(itemView){

public abstract class MvpViewHolder<P extends BasePresenter> extends RecyclerView.ViewHolder {
    protected P presenter;

    public MvpViewHolder(View itemView) {
        super(itemView);
    }

    public void bindPresenter(P presenter) {
        this.presenter = presenter;
        presenter.bindView(this);
    }

    public void unbindPresenter() {
        presenter = null;
    }
}


这是我的科特林尝试

abstract class MvpViewHolder<P : BasePresenter>(itemView: View) : RecyclerView.ViewHolder(itemView) {

    protected var presenter: P? = null

    fun bindPresenter(presenter: P?): Unit {
        this.presenter = presenter
        presenter?.bindView(this)

    }

    fun unbindPresenter(): Unit {
        this.presenter = null
    }
}


我特别遇到泛型问题。事实证明,在Kotlin中,仅仅执行MvpViewHolder<P : BasePresenter>是远远不够的,因为Kotlin要求我们为BasePresenter传递2个类型的参数(我在下面提供了其实现)

但是,如果我需要为BasePresenter传递类型参数,那么我的方法签名将如下所示

`abstract class MvpViewHolder<P : BasePresenter<*, *>>(itemView: View) : RecyclerView.ViewHolder(itemView) {`


但是,这对我没有帮助,因为在presenter.bindView(this)中,出现类型错误Required: Nothing, Found: MvpViewHolder

我也可以更具体地传递
MvpViewHolder<P: BasePresenter<M, V>, M, V>,但这意味着无论我叫MvpViewHolder哪里,我都还必须包括2个额外的类型参数。现在必须维护这不仅会很乏味,而且让我很难过。

当我使用BasePresenter 时如何摆脱错误,或者避免必须将3个类型参数传递给我的MvpViewHolder类,因此我可以将P定义为BasePresenter

abstract class BasePresenter<M, V> {
    var model: M? = null

    var view: WeakReference<V>? = null

    fun setM(model: M?): Unit {
        this.model = model

        if (setupDone()) {
            updateView()
        }
    }

    fun bindView(view: V) {
        this.view = WeakReference(view)
    }

    fun unbindView() {
        this.view = null
    }

    abstract fun updateView()

    fun view(): V? {
        return if (view == null) null else view?.get()
    }

    fun setupDone(): Boolean {
        return view() != null && model != null
    }

}

最佳答案

将抽象类更改为以下代码

 abstract class MvpViewHolder<P :BasePresenter<P,MvpViewHolder<P>>>(itemView: View) : RecyclerView.ViewHolder(itemView) {
        protected var presenter: P? = null
        fun bindPresenter(presenter: P) {
            this.presenter = presenter
            presenter.bindView(this)
        }

        fun unbindPresenter() {
            presenter = null
        }
    }

09-28 05:03