Java vs Kotlin泛型

时间:2017-11-03 04:15:51

标签: java generics kotlin kotlin-android-extensions

我有以下Java类,我试图转换为使用泛型的Kotlin。

抽象类MvpViewHolder,M,V:View?>(itemView:View):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;
    }
}

这是我的Kotlin尝试

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中,由于Kotlin要求我们传递BasePresenter的2个类型参数(我在下面的实现中),所以MvpViewHolder<P : BasePresenter>根本不够;

但是,如果我需要传入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&lt; &gt;时,如何摆脱错误?或者避免将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
    }

}

1 个答案:

答案 0 :(得分:1)

将抽象类更改为以下代码

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