Kotlin 函数需要 Nothing but defined as a different type

Kotlin function required Nothing but defined as a different type

我已经这样定义了一个 class

abstract class MvpViewHolder<P>(itemView: View) : RecyclerView.ViewHolder(itemView) where P : BasePresenter<out Any?, out Any?> {
    protected var presenter: P? = null

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

其中 presenter.bindView(itemView) 给我一个错误,指出 Type mismatch, required: Nothing, found: View!。我已经在 presenter class 中定义了 bindView ,就像这样

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

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

它正在接受 view: V 的值。

我尝试使用星号语法 BasePresenter<*,*> 定义 BasePresenter<out Any?, out Any?> 的扩展名,但我遇到了同样的错误。我也试过简单地使用 BasePresenter<Any?, Any?> 来解决直接问题,但是任何扩展 P: BasePresenter<Any?, Any?> 的东西都会出错,说它期待 P,但得到了 BasePresenter<Any?, Any?>

这是一个在我的代码中发生的例子

abstract class MvpRecyclerListAdapter<M, P : BasePresenter<Any?, Any?>, VH : MvpViewHolder<P>> : MvpRecyclerAdapter<M, P, VH>() {...}

在这一行中,我会在 extends MvpRecyclerAdapter<M, P, VH>

部分得到上面提到的错误

我似乎无法解决这个问题。我该如何解决?

您已在 BasePresenter<out Any?, out Any?> 处为通用参数 V 声明了 out,因此 presenter.bindView 不得采用输入参数。

解决方案:将声明更改为BasePresenter<out Any?, View?>

查看 official doc 了解更多信息。