【问题标题】:Kotlin function required Nothing but defined as a different typeKotlin 函数只需要定义为不同的类型
【发布时间】:2017-11-02 01:28:15
【问题描述】:

我已经定义了一个这样的类

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 类中定义了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&lt;*,*&gt; 定义我的BasePresenter&lt;out Any?, out Any?&gt; 扩展,但我得到了同样的错误。我也尝试过仅使用 BasePresenter&lt;Any?, Any?&gt; 来解决直接问题,但是任何扩展 P: BasePresenter&lt;Any?, Any?&gt; 的东西都会出错,说它期待 P,但得到了 BasePresenter&lt;Any?, Any?&gt;

这是在我的代码中发生的示例

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

在这一行上,我会在扩展MvpRecyclerAdapter&lt;M, P, VH&gt; 部分得到上述错误

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

【问题讨论】:

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


    【解决方案1】:

    您已在BasePresenter&lt;out Any?, out Any?&gt; 为泛型参数V 声明out,因此presenter.bindView 不得采用输入参数。

    解决方案:将声明更改为BasePresenter&lt;out Any?, View?&gt;

    查看official doc了解更多信息。

    【讨论】:

    • 它仍然会给我这一行的错误 abstract class MvpRecyclerListAdapter&lt;M, P : BasePresenter&lt;Any?, View?&gt;, VH : MvpViewHolder&lt;P&gt;&gt; : MvpRecyclerAdapter&lt;M, P, VH&gt;() {...} 说明,特别是对于 Pexpects P` 但找到 BasePresenter
    • @Rafa 不应该在你的泛型中使用P 到处都是P : BasePresenter&lt;Any?, View?&gt; .. 我的意思是泛型很好,但你已经和他们一起去了城里......
    • 你是对的。是的,我正在使用 MVP 启动一个应用程序,我正在尝试将此代码转换为 Kotlin github.com/remind101/android-arch-sample/tree/master/app/src/… 事实证明,将通用签名转换为 Kotlin 非常困难
    • @Rafa,您是否解决了上述这些问题,我正在尝试将相同的代码转换为 Kotlin
    猜你喜欢
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多