Can Someone Explain This Recycler View Adapter For Me, The Class Header And Such

- 1 answer

Im trying to create an app with a recyclerview, and I am trying to figure out the following code from an android example. Like what is the onClick value they are putting in the first class, and what is the lambda expression for and what does it do? I notice a similar lambda is in the class below it as well. If anyone can please explain the code. Thank you.

class FlowersAdapter(private val onClick: (Flower) -> Unit) :
ListAdapter<Flower, FlowersAdapter.FlowerViewHolder>(FlowerDiffCallback) {

/* ViewHolder for Flower, takes in the inflated view and the onClick behavior. */
class FlowerViewHolder(itemView: View, val onClick: (Flower) -> Unit) :
    RecyclerView.ViewHolder(itemView) {
    private val flowerTextView: TextView = itemView.findViewById(
    private val flowerImageView: ImageView = itemView.findViewById(
    private var currentFlower: Flower? = null

    init {
        itemView.setOnClickListener {
            currentFlower?.let {

    /* Bind flower name and image. */
    fun bind(flower: Flower) {
        currentFlower = flower

        flowerTextView.text =
        if (flower.image != null) {
        } else {


The onClick parameter has a type of (Flower) -> Unit. That represents a function, which takes a single Flower parameter (in the parentheses) and returns Unit (i.e. "doesn't return anything").

That means that onClick is a function, and you can call it like onClick(someFlower), which is what's happening in that click listener set up in the init block. The naming might make it a little confusing, but it's basically this:

  • pass in some handler function
  • set up a click listener on itemView
  • when itemView is clicked, call the handler function, passing currentFlower

so it's just a way for you to provide some behaviour to handle a flower being clicked. You still need the click listener - that's a thing that operates on a View and handles click interactions. But inside that listener, you can do what you like when the click is detected, and in this case it's running some externally provided function