Kotlin通用类

时间:2019-07-02 17:38:01

标签: class generics kotlin

我是Kotlin的新手,正在尝试访问泛型类中的特定字段

我尝试了各种可能的解决方案-我遇到的问题是,我不知道如何通知Kotlin我经过的类中的字段名称存在。

这是我的课程:-

@Entity(tableName = "coursemark_table")
@Parcelize
class CourseMark(
    @field:PrimaryKey
    @field:ColumnInfo(name = "coursemark_number")
    var number: Int,
    var name: String,
    var latitude: String,
    var longitude: String,
    var passTo: String
): Parcelable

这是我要初始化的通用列表适配器类-我不知道如何在OnBindViewHolder函数中获取CourseMark中的名称字段,我可以理解为什么原因,因为BaseListHolder不了解其中的字段名称CourseMark直到它初始化为止,但必须有一种方法告诉Kotlin编译器该字段存在-对此表示歉意,但我已经努力了好几天才能弄清楚:-

abstract class BaseListAdapter<T> internal constructor(context: Context) :
    RecyclerView.Adapter<BaseListAdapter<T>.BaseViewHolder>() {

    private val mInflater: LayoutInflater = LayoutInflater.from(context)
    private var mMarks = emptyList<T>() // Cached copy of marks

    inner class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val markItemView: TextView = itemView.findViewById(R.id.textView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val itemView = mInflater.inflate(R.layout.recyclerview_coursemark, parent, false)
        return BaseViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        val current = mMarks[position]
        holder.markItemView.text = current.name
    }

    /**
     * Associate a list of marks with this adapter
     */

    internal fun setMarks(marks: List<T>) {
        mMarks = marks
        notifyDataSetChanged()
    }

    // getItemCount() is called many times, and when it is first called,
    // mMarks has not been updated (means initially, it's null, and we can't return null).
    override fun getItemCount(): Int {
        return mMarks.size
    }

    /**
     * Get the mark at a given position.
     * This method is useful for identifying which mark
     * was clicked or swiped in methods that handle user events.
     *
     * @param position
     * @return The mark at the given position
     */
    fun getMarkAtPosition(position: Int): T {
        return mMarks[position]
    }

}

1 个答案:

答案 0 :(得分:1)

您最好的选择是使用指定的类型RecyclerView.Adapter实现CourseMark。当您放大看起来是CourseMark类专用的布局时,我不清楚您为什么要保持适配器通用。

但是,如果您确实希望保留此通用名称,则可以在onBindViewHolder方法中利用Kotlin的智能转换:

override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
    val current = mMarks[position]
    if(current is CourseMark){
         holder.markItemView.text = current.name
    }
}