How to refer to "this" in anonymous listeners when using short notation?

In Kotlin, is there a way to refer to a listener instance when using this short notation for anonymous classes? In this case, this refers to an external context (for example, an Activity instance), where view is defined:

 view.setOnClickListener { val self: View.OnClickListener = this // Not compiling, "this" references outer context } 

When using a longer notation in which you explicitly specify the interface to be implemented, and where you explicitly override the callback method, the listener can be referenced via this :

 view.setOnClickListener(object: View.OnClickListener { override fun onClick(v: View) { val self: View.OnClickListener = this // Ok } }) 
+6
source share
2 answers

The term short notation for anonymous classes is not entirely correct. This is actually a short notation for anonymous functions, i.e. Lambda. Of course, under the hood they are compiled for classes, but from the point of view of the programming language, anonymous functions do not have identities, and therefore it makes no sense to refer to their instances via this .

+6
source
  val animation = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { val layoutParam: RelativeLayout.LayoutParams? = playerView.layoutParams as RelativeLayout.LayoutParams? layoutParam?.topMargin = convertDpToPixel(position, this@SurahActivity ).toInt() playerView.layoutParams = layoutParam } } 
-2
source

Source: https://habr.com/ru/post/986354/


All Articles