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
    }
})

推荐答案

匿名类的短期表示法并不完全正确.它实际上是匿名函数的一个简短符号,即lambdas.当然,在后台它们被编译成类,但从编程语言的Angular 来看,匿名函数没有标识,因此通过this引用它们的实例是没有意义的.

Kotlin相关问答推荐

如何在Jetpack Compose中从领域查询中读取数据?

Scala性状线性化等价于Kotlin

如何修改muableStateMapOf的值?

如何在Docker中使用Selenium和chromedriver?

如何更改默认推断没有接收者的函数类型?

同时也是一个字符串的 Kotlin 枚举

为什么在jacksonObjectMapper上将DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES设置为false无效?

使用调度程序运行异步 Kotlin 代码

Kotlin 函数有 2 个参数用于对 Map 或 List 进行排序

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

第二个协程永远不会执行

Picasso 回调

Kotlin 无法找到或加载主类

如何从 Java 中隐藏 Kotlin 的 lateinit var 支持字段?

如何在 Kotlin 中使用 volatile

如何从 Firestore 查询中排除元素?

禁用 IntelliJ kotlin * 导入?

指定为非null的参数在ArrayAdaper中为null

从 java 活动 *.java 启动 kotlin 活动 *.kt?

Dagger 2 androidx fragment不兼容类型