Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create object of a reified type in Kotlin

I was trying to create an extension function to create object of view holder for recycler view adapter

inline fun <reified T: RecyclerView.ViewHolder> ViewGroup.createViewHolder(@LayoutRes res: Int): T {
    val inflater = LayoutInflater.from(context)
    val itemView = inflater.inflate(res, this, false)
    // return ViewHolder Object
}

How do I create an object of the type T that extends RecyclerView.ViewHolder so that I can return from the function.

like image 691
Samuel Robert Avatar asked May 24 '18 13:05

Samuel Robert


1 Answers

A clean alternative solution is to pass the constructor explicitly. It won't even be more verbose, because the type parameter can be inferred and doesn't need to be specified any more. Use like this:

val viewHolder = my_view_group.create(::MyViewHolder, R.layout.my_layout)

Implement like this:

inline fun <reified T: RecyclerView.ViewHolder> ViewGroup.create(createHolder: (View) -> T, @LayoutRes res: Int): T {
    val inflater = LayoutInflater.from(context)
    val itemView = inflater.inflate(res, this, false)
    return createHolder(itemView)
}
like image 80
Robert Jack Will Avatar answered Sep 22 '22 18:09

Robert Jack Will