https://kotlinlang.org logo
a

arild

03/16/2017, 7:59 PM
I’m having an issue with passing lambdas or bound instance methods as listeners: say I have
Copy code
class SomeClass {
    val myEventListener = { log(”got event ${it) }

    fun onEventProducerAttached(producer: EventProducer) {
        log(”hashcode before passing listener: ${myEventListener.hashCode()}“)
        producer.addEventListener(myEventListener)
    }

    fun onEventProducerDetached(producer: EventProducer) {
        producer.removeEventListener(myEventListener)
    }
…
class EventProducer {
    ...
    addEventListener(listener: () -> Unit) {
        log(”hashcode when receiving passed listener: ${myEventListener.hashCode()}“)
        ...
    }
}
the addEventListener receives a different instance in
addEventListener
and
removeEventListener
. More explicitly: the haschode recorded in the log from the passing code and the receiving code will be different. Unless I am mistaken about this behaviour, I think this should be made very clear in the Kotlin reference to avoid people stumbling over it (as I have done for the last hour). Also, if there already exists documentation to read up on the implementation of lambdas and method references and why the behaviour I describe above is as it is, I would be very grateful if someone could point me towards it.