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

标签 android generics kotlin kotlin-android-extensions kotlin-extension

我定义了一个这样的类

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! .我已经定义了 bindViewpresenter里面像这样上课

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<out Any?, out Any?> 的扩展名使用星号语法 BasePresenter<*,*>但我得到了同样的错误。我也试过简单地使用 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获取更多信息。

关于android - Kotlin 函数需要 Nothing but defined as a different type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47066168/

相关文章:

java - Android - 找到一个 ImageView 然后设置它的可见性

java - 无界通配符参数化类型数组的实际用法是什么?

android - 如何设置 Kotlin 版本

android - Dokka - 跳过为默认的 android 包生成 javadoc

java - PayPal 沙箱 API 不允许买家登录

android - 从非 PreferenceActivity/Fragment 更改首选项值

安卓 : missing package statement; Activity class does not exist

C# 获取给定 T 的类型 Generic<T>

java - 如何用 Java 构建通用实体存储库

android - 如何使用 Android CameraX API 缩放相机?