Different function reference values to the same method

Got an interesting behavior, when the callback added with
viewTreeObserver.addOnGlobalLayoutListener(::layoutCallback)
is working properly, but can’t be removed with
viewTreeObserver.removeOnGlobalLayoutListener(::layoutCallback)

during debugging appeared, that ::layoutCallback has different value compared to the first usage.

Is it expected or a bug?

It is how function references work in Kotlin. You can fix that by storing a lambda expression or function reference in a private property, then use that property to add and remove the listener.

Thanks for a prompt reply. I also found the way to workaround - either via variable of function type (as you suggested) or via the “old style” ViewTreeObserver.OnGlobalLayoutListener and passing this to add/remove listener.

Anyway, that looks confusing. Especially for people coming from C/C++, where a pointer to function is always the same and they can’t even imagine it can be different each time :slight_smile:

I did not find if it is documented (I might be wrong). It would be very helpful if it gets documented and compiler/IDE warn about possible hidden problems.

Thank you, filed a task to document this at https://youtrack.jetbrains.com/issue/KT-31698.

1 Like