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
}
})
When a source, such as a website or an older anonymous text, doesn’t list an author, MHRA recommends starting your footnotes and bibliography entry with the title. In these cases, the source is also alphabetised by title in your bibliography: When a source does not list a publication date, the term ‘ [n.d.]’ (no date) is used in place of the year.
Another approach, which is the standard way since DOM2 to bind this within the event listener, that let you always remove the listener (among other benefits), is the handleEvent (evt) method from the EventListener interface:
The handleEvent method can be used for multiple events. You can specify logic by using event.type. Back to the Dragger class. So now I add the handleEvent method to cooridate which event method to trigger. Then I can add this as the event listener. So to the original question: this can be used as an event listener as it has a handleEvent method.
Note that when a source lacks an author and is therefore listed by title, it is alphabetised according to the first word of the title, as with Napoleonic Wars. When more than one of an author’s works are listed, the author’s name can be replaced with a double em dash (——) for the second and subsequent works:
You can get that resolved by adding an @ActivityName in front of 'this' reference For example if your Activity name was MainActivity the solution would be:
view.setOnClickListener {
val self: View.OnClickListener = this@MainActivity
}
The term short notation for anonymous classes is not entirely correct. It's actually a short notation for anonymous functions, i.e. lambdas. Of course under the hood they are compiled to classes but from a programming language point of view, anonymous functions don't have identities and therefore it doesn't make sense to refer to their instances via this
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With