7

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?

2
  • 2
    "Of course it doesn't compile" So what is the full, exact error message you're getting?
    – Michael
    Feb 12, 2018 at 11:29
  • someObject.removeListener(this) . Check zsmb13's answer Feb 12, 2018 at 11:35

2 Answers 2

14

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)
        }
    }
}
1
  • thanks a lot for the answer and as far as I tested here, that indeed is the correct answer for a interface. Please check my edit on the question, I just realized later that it's actually a code: (T) -> kotlin.Unit that I'm using. Is that possible ?
    – Budius
    Feb 12, 2018 at 12:58
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 })
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.