How are functions compared for equality in Kotlin? Referential equality? Type equality?
For context, I’m storing a collection of event handlers of type (Event<T>) -> Unit and got to wondering how contains and indexOf actually work when each element in the collection are functions.
fun main() {
val v = 5
val f1 = { v == 5 }
val f2 = { v == 5 }
val f3 = f1
println("by type or definition: ${f1 == f2}" )
println("by reference: ${f1 == f3}" )
}
Of course, and it will show the exact same result with === as well. So my question was more exactly doesn’t Function1<T,U>.equals(other: Function1<T,U>): Boolean check by reference anyway?
And that’s the default equality implementation of Any.
But function type are interfaces. It’s pretty easy, though maybe ill-advised, to implement it with your own class and override equals to anything you want.
The OP seemed to think that there might be some other implementation for built-ins, so I tried to show that even if two different functions have the same definition, they won’t be considered equal in his scenario (it prints false there).
Thanks everyone. I was wondering if it boiled down to the default reference equality implementation from Any, or if some sort of function signature matching is done. I think everyone has pretty well sorted me out, I appreciate it!