【问题标题】:Why I can't use a Class type as a generic parameter in Kotlin?为什么我不能在 Kotlin 中使用 Class 类型作为泛型参数?
【发布时间】:2020-07-01 01:39:30
【问题描述】:

我在一个使用 Kotlin 的 Android 应用程序中工作,但是当我尝试使用具体类作为第四个参数时出现错误,我的问题是,我做错了什么?

这是 RecyclerView 的基本适配器

abstract class BaseAdapter<K, T: DbEntity<K>, VDB: ViewDataBinding, VH: BaseViewHolder<K,DbEntity<K>, VDB>>: RecyclerView.Adapter<VH>(){
    val items: MutableList<T> = ArrayList()

    fun addNewItems(newItems: List<T>){

    }
}

这是我用于指定泛型参数的类,但出现错误

class CaseByCountryViewHolder(mDataBinding: ItemCaseByCountryBinding): BaseViewHolder<Int, CaseByCountry, ItemCaseByCountryBinding>(mDataBinding) {

    override fun bind(item: CaseByCountry) {
    }
}

这是基本 ViewHolder 类:

abstract class BaseViewHolder<K, T: DbEntity<K>, VDB: ViewDataBinding>(mDataBinding: ViewDataBinding)
    :RecyclerView.ViewHolder(mDataBinding.root){
    protected val context: Context = mDataBinding.root.context
    protected val layoutInflater: LayoutInflater = LayoutInflater.from(context)
    abstract fun bind(item: T)
}

最后,这是我得到的错误:

你能帮帮我吗?我不知道我做错了什么,提前谢谢。

【问题讨论】:

  • 你能发布你的 CaseByCountry 课程吗?
  • 这里,class BaseAdapter&lt;K, T: DbEntity&lt;K&gt; 你可以将这个T 直接传递给abstract class BaseAdapter&lt;K, T: DbEntity&lt;K&gt;, VDB: ViewDataBinding, VH: BaseViewHolder&lt;K,DbEntity&lt;K&gt;, VDB&gt;&gt; 而不是DbEntity&lt;K&gt;
  • @AkshayNandwana 多亏了你,问题解决了,应该是答案了,非常感谢。

标签: android generics kotlin inheritance


【解决方案1】:

这只是一个参数传递错误。

abstract class BaseAdapter<K, t : A<K>, 
VDB: ViewDataBinding, VH: BaseViewHolder<K,t, VDB>>{ }

class CaseByCountryAdapter() 
: BaseAdapter<Int, CaseByCountry, ViewDataBinding, CaseByCountryViewHolder>()

abstract class BaseViewHolder<K, t : A<K>, VDB: ViewDataBinding> {}

class CaseByCountryViewHolder(mDataBinding: ItemCaseByCountryBinding)
: BaseViewHolder<Int, CaseByCountry, ViewDataBinding>() {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多