首页 > 解决方案 > 为什么我不能在 Kotlin 中使用 Class 类型作为泛型参数?

问题描述

我正在使用 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)
}

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

你能帮我吗?我不知道我做错了什么,在此先感谢。

标签: androidgenericskotlininheritance

解决方案


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

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>() {}

推荐阅读