返回为Pair <>的类的名称

时间:2018-08-17 15:43:06

标签: java kotlin

Kotlin 1.2.30

我在委托适配器中实现以下接口;

interface ItemDelegate<H : RecyclerView.ViewHolder, I> {
    fun itemType(): Class<out I>
    fun createHolder(parent: ViewGroup): H
    fun bindView(holder: H, item: I)
}

我必须返回类的名称,但由于它是Pair<String, ApartmentItems.ApartmentDescription>,所以我不确定如何返回该类:

override fun itemType(): Class<out Pair<String, ApartmentItems.ApartmentDescription>> {
    return Pair<String, ApartmentItems.ApartmentDescription>::class.java
}

在实现AdapterDelegate的过程中,我具有以下内容:

class ApartmentDescriptionDelegate
    : ItemDelegate<ApartmentDescriptionViewHolder, Pair<String, ApartmentItems.ApartmentDescription>> {

    override fun itemType(): Class<out Pair<String, ApartmentItems.ApartmentDescription>> {
        return Pair<String, ApartmentItems.ApartmentDescription>::class.java
    }

    override fun createHolder(parent: ViewGroup): ApartmentDescriptionViewHolder {
        return ApartmentDescriptionViewHolder(parent)
    }

    override fun bindView(holder: ApartmentDescriptionViewHolder, item: Pair<String, ApartmentItems.ApartmentDescription>) {
        holder.apartmentOverviewDescription.text = item.second.description
    }

    class ApartmentDescriptionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val apartmentOverviewDescription: TextView = itemView.findViewById(R.id.description)
    }
}

我尝试执行以下操作: 返回Pair :: class.java

但是我收到一条错误消息:

Only class names are allowed on the left hand side of a class literal

1 个答案:

答案 0 :(得分:1)

您可以像这样投射它以使Kotlin开心:

override fun itemType(): Class<out Pair<String, ApartmentItems.ApartmentDescription>> {
    @Suppress("UNCHECKED_CAST")
    return Pair::class.java as Class<Pair<String, ApartmentItems.ApartmentDescription>>
}