如何引用"this"?在使用短记号的匿名侦听器中? [英] How to reference "this" within anonymous listeners when using short notation?
问题描述
在Kotlin中,当对匿名类使用这种简短表示法时,是否有一种方法可以引用侦听器实例?在这种情况下,this
指的是定义了view
的外部上下文(例如Activity
实例):
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
}
在使用更长的表示法明确声明要实现的接口并明确覆盖回调方法的位置时,可以通过this
引用侦听器:
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
}
})
推荐答案
术语匿名类的简称不是完全正确的.实际上,这是匿名函数(即lambdas)的缩写.当然,它们在内部被编译为类,但是从编程语言的角度来看,匿名函数没有身份,因此通过this
引用它们的实例是没有意义的.
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
.
这篇关于如何引用"this"?在使用短记号的匿名侦听器中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!