Remove “this” callback in kotlin

后端 未结 2 1923
谎友^
谎友^ 2021-01-18 18:55

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 follo

相关标签:
2条回答
  • 2021-01-18 19:41

    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 })
       }
    }
    
    0 讨论(0)
  • 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)
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题