Is there a way to check if lambda val bodies are t...
# getting-started
b
Is there a way to check if lambda val bodies are the same? I've tried checking by hashCodes, but those are still different for identical lambdas
b
So you create two lambdas with identical bodies and want to know if their bodies match? Do I get it right?
b
Correct
E.g.
Copy code
val f1 = {
  println(1)
}
val f2 = {
  println(1)
}
val f3 = {
  println(2)
}

fun same(one,other):Boolean = TODO()

same(f1,f2) // true
same(f1,f3) // false
b
I think lambdas are basically anonymous classes which implements interface with your function, so when you create your lambdas you create two anonymous classes and their hashcodes is generated randomly by machine, that's why they don't match. I have two workarounds in mind you can return something from your lambdas and compare them or create wrapper class for it and then you will be able to generate hashcode by yourself.
b
Hmm, don't think i can use that in my case. Is there a way to get its string representation like in js for example?
b
No there is not, I'm gonna try to Google your problem but I don't think it can be achieved without huge head pain, I would instead encourage you to find some other workaround which would work in your case
j
Why create multiple identical lamda instances? Why not create 1 and inject it everywhere?
b
It's just an example. My use case is dealing with registering and removing event listeners
s
Why would deregistering with a new lambda of the same body deregister the first one? I would let the caller keep a reference to the lambda to deregister it, or introduce ids to identify them
k
Define your own type for the lambda and let the caller to implement their own compare function.
☝️ 1
j
I think the observer will have to maintain a reference to the lambda that it registered, in order to later use that same lamda instance to identify the listener to be removed. A different direction may be to create a data class that extends a function type. You may need to override the equals behavior. You would no longer be dealing with anonymous functions. But you would be able to instantiate instances of functions and compare them by value, not by reference. This would free you from having to store a reference to the listener just so that you can deregister the listener later. That is, at deregistration time you could create a new instance of the listener and it would pass the test of being equal to the original listener.