【问题标题】:How to create object of generic type in a class如何在类中创建泛型类型的对象
【发布时间】:2018-05-07 06:51:53
【问题描述】:

我有以下课程

open abstract class NexusAdapter<TData: NexusIdProvider, TViewHolder: NexusViewHolder<TData>>
                (protected val ctx: Context, private val _layoutId: Int, protected val items: List<TData>):
                BaseAdapter() {

    override fun getView(position: Int, view: View?, parent: ViewGroup?): View {
        val itemView = if (view == null)
            LayoutInflater.from(ctx).inflate(_layoutId, parent, false)
                else view!!

        // How do I create the object of type TViewHolder at runtime????
        var viewHolder: TViewHolder = TViewHolder::class.java.newInstance()

        viewHolder.bind(itemView , getItem(position))
        return itemView
    }

    //...
}

如何在我的类中创建TViewHolder 类型的对象。

【问题讨论】:

    标签: android generics kotlin constructor-reference


    【解决方案1】:

    你不能这样做。您必须为其提供工厂方法。

    在类中使用抽象函数

    abstract fun createViewHolder(): TViewHolder
    

    或将其作为参数提供给构造函数

    abstract class NexusAdapter<TData: NexusIdProvider, TViewHolder: NexusViewHolder<TData>>(
            protected val ctx: Context,
            private val _layoutId: Int,
            protected val items: List<TData>,
            private val createViewHolder: () -> TViewHolder
    ) : BaseAdapter()
    

    【讨论】:

      猜你喜欢
      • 2023-01-09
      • 2014-04-04
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多