I recently found myself writing the following code:
fun listener() {
// Do some stuff
adapter.removeLoadStateListener(::listener)
}
adapter.addLoadStateListener(::listener)
A colleague remarked on the fact that
val x1 = ::listener
val x2 = ::listener
x1 == x2 //true
x1 === x2 //false
However,
var mySet = mutableSetOf<() -> Unit>()
fun a() { }
fun b() { }
mySet.add(::a)
mySet.add(::b)
mySet.remove(::a)
mySet.contains(::a) // false
mySet.contains(::b) // true
Based on this I get the impression I do not understand ::myFun properly and I start to question if my original code is safe to use.
TL;DR
- Is it safe to use
::listenerto reference a method to be used as a listener and that will need to be referenced multiple times (e.g. add + remove)? - What is actually going on behind the scenes regarding anonymous classes etc.?
EDIT
Eventually we decided against using ::listener for this case. However, we ran into a new problem since add/removeLoadStateListener will only accept the (CombinedLoadState) -> Unit type.
I'll leave our solution to that problem here for future reference and other readers as it is related (I expect some may even come here looking for this rather than answers to the original question):
val listener = object : (CombinedLoadStates) -> Unit {
override operator fun invoke(loadState: CombinedLoadStates) {
// Do some stuff
adapter.removeLoadStateListener(this)
}
}
adapter.addLoadStateListener(listener)