Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a lambda instead of a kotlin interface

I have a recycler view adapter in android. Part of my adapter class looks like this:

private lateinit var itemLongClick: ItemLongClick

override fun onCreateViewHolder(parent: ViewGroup, a: Int): RecyclerAdapter.ViewHolder {

      // Define And Initialize The Custom View And Its Holder//
      val myView = LayoutInflater.from(parent.context).inflate(customLayout, parent, false)
      val viewHolder = ViewHolder(myView)

      // What Happens When A List Item Is Long Clicked//
      myView.setOnLongClickListener { view ->

          // Differ Action To Class Instance//
          itemLongClick.longClicked(context, viewHolder.layoutPosition, view)

          // End Function//
          true
      }

      // Returns The Custom View//
      return viewHolder
}

fun setItemLongClick(itemLongClick: ItemLongClick) {

    // Sets The Value For this.itemLongClick//
    this.itemLongClick = itemLongClick
}    

I created an interface tat looks like this:

interface ItemLongClick {

    // Function Declaration For When An Item Is Long Clicked//
    fun longClicked(context: Context, position: Int, view: View)
}

Instead of writing my on long click code in the adapter class I want to differ it to the activity that is calling the adapter class. I know one way of doing this is to make a kotlin interface then call it in the other class like this

  userAdapter.setItemLongClick(object: ItemLongClick {
        override fun longClicked(context: Context, position: Int, view: View) {

        }
    })

But this looks messy. I know java interfaces work with SAM but I don't want to do that either. What I want is for the onLongClick to be a Lambda but I'm not sure how to set up a Kotlin lambda expression to make this work and I can't find a good example anywhere.

Thanks in advance

like image 426
Jordan Avatar asked Jan 02 '23 08:01

Jordan


1 Answers

You have two options:

1.) replace interface with typealias

typealias ItemLongClick = (Context, Int, View) -> Unit

2.) add an extension function for setting the interface as a lambda instead of with anonymous object

inline fun UserAdapter.setItemLongClick(crossinline longClick: (Context, Int, View) -> Unit) {
    setItemLongClick(object: ItemLongClick {
        override fun longClicked(context: Context, position: Int, view: View) {
            longClick(context, position, view)
        }
    })
}

Now you can call

userAdapter.setItemLongClick { context, position, view -> 
    ...
}
like image 178
EpicPandaForce Avatar answered Jan 05 '23 04:01

EpicPandaForce