删除"this" Kotlin中的回调 [英] Remove "this" callback in kotlin
问题描述
我是Kotlin的新手,我想删除回调本身中的回调实例.
I'm a bit kotlin newbie and I'm trying to remove the callback instance inside the callback itself.
我要实现的目标类似于以下代码.
What I'm trying to achieve it's something similar to the following code.
private val myCallback = SomeInterfaceType {
if(it.something) {
someObject.removeListener(this@SomeInterfaceType)
}
}
当然,它不会编译,否则我不会在这里询问.所以我问,如何从接口实例内部删除回调?
Of course it doesn't compile or else I wouldn't be asking here. So I ask, how to remove the callback from inside the instance of the interface?
修改: 错误为推断的类型为X,但应为Y.
edit: the error is "inferred type is X but Y was expected.
我刚刚意识到我问错了一个问题,它与之类似,但不完全是一个接口.
edit 2: I just realized I've asked the wrong question, it's similar to it but not exactly a Interface.
我正在使用的对象具有以下构造函数/接口
The object I'm using have the following constructor/interface
public open class Watcher<T> public constructor(call: (T) -> kotlin.Unit)
public open class Watcher<T> public constructor(call: (T) -> kotlin.Unit)
因此,实际上,我正在尝试从call: (T) -> kotlin.Unit
内部引用观察者以删除侦听器.
so in reality I'm trying to reference the Watcher from inside the call: (T) -> kotlin.Unit
to remove the listener.
有可能吗?
推荐答案
您需要使用完整的对象表达式引用的语法能够引用实例本身:
You need to use a full object expression syntax to refer to be able to refer to the instance itself:
private val myCallback = object: SomeInterfaceType() {
override fun onSomeEvent() {
if (it.something) {
someObject.removeListener(this)
}
}
}
这篇关于删除"this" Kotlin中的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!