In Kotlin, is there a way to reference the listener instance when using this short notation for anonymous classes? In this case this
refers to outer context (e.g. the Activity
instance) where view
is defined:
view.setOnClickListener {
val self: View.OnClickListener = this // Not compiling, "this" references outer context
}
When using the longer notation where you explicitly state the interface to be implemented and where you explicitly override the callback method, the listener can be referenced through this
:
view.setOnClickListener(object: View.OnClickListener {
override fun onClick(v: View) {
val self: View.OnClickListener = this // Ok
}
})