1

I have a situation similar to the following example and when I call this it references the Activity not the OnClickListener. Is there way to make this a reference of the listener?

private fun onClick() = View.OnClickListener {
    // How to make 'this' a reference of OnClickListener instead of the Activity
}
Felipe Belluco
  • 1,102
  • 10
  • 12

1 Answers1

2

The easiest way to achieve this is by using the object syntax as opposed to lambda (although it’s a bit more noisy to use):

private fun onClick() = object: View.OnClickListener {
    override fun onClick(v: View){
        //this in the context of listener
    }
}

Otherwise, you’d have to wrap the implementation into another higher-order function that works with lambdas with receiver. Would be overkill here I think.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • The object syntax worked very perfectly! I knew that one day lambda wouldn't be there for me... I just thought it would last a little longer! – Felipe Belluco Jan 29 '18 at 03:14