Equality of Functions

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.

Function1<Event<T>, kotlin.Unit>
This is what the type of your function will be.

Easy to check:

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}" )
1 Like

Aren’t you comparing by reference anyway in both cases?

1 Like

In Kotlin, == is for equality and really calls .equals(). If you want to use referential equality you can use ===

Try editing nick’s post in the forum. Replacing the “==” with “.equals()” in his post and rerunning it will show the same result.


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?

In general, yes, it’s by reference.

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).

1 Like

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!

1 Like