Remove “this” callback in kotlin

2020-04-11 09:50发布

问题:

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?

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)

so in reality I'm trying to reference the Watcher from inside the call: (T) -> kotlin.Unit to remove the listener.

Is that possible?

回答1:

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


回答2:

There's also a workaround: wrap the reference to myCallback into a lambda passed to a function that calls it (e.g. run { ... }):

private val myCallback: SomeInterfaceType = SomeInterfaceType {
   if (it.something) {
        someObject.removeListener(run { myCallback })
   }
}