How to create object of generic type in a class

239 views Asked by At

I have the following class

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
    }

    //...
}

How do I create the object of type TViewHolder in my class.

1

There are 1 answers

0
tynn On

You cannot do this. You'd have to provide a factory method for it.

Either have it with an abstract function within the class

abstract fun createViewHolder(): TViewHolder

or provide it as a parameter to the constructor

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