Kotlin Android Extensions with ViewHolders

Something I recently discovered is how easy it is to use Kotlin’s Android View extensions with RecyclerView ViewHolders. Previously using Butterknife, many of my ViewHolder classes were simply a bunch of @BindViews with an init { ButterKnife.bind } . With Kotlin Android extensions, the views are declared as extensions on the ViewHolder’s ItemView field; now my ViewHolder classes are simply one line, and I use a viewHolder.itemView.let { } in my bind methods.

You could potentially use any of Kotlin’s scoping extensions functions, I prefer to use let, so here’s what that looks like:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val item = this[position]
    holder.itemView.let {
        it.viewIdTitle = item.title
        it.viewIdDescription = item.description
    }
}

class ViewHolder(v: View) : RecyclerView.ViewHolder(v)