Why does Kotlin allow member and extension function with same signature?

Kotlin allows both member functions and extension functions to coexist even if they have the same signature.

Why did Kotlin allow this and decide not to show error during compilation? This makes the existing code fragile during dependency updates.

2 Likes

Hum interesting. Probably because extensions are static so they are not in the same scope.

Anyway it should be ban by the compiler as it is not truly direct type statics.

One potential reason is that there are situations in which it can’t disallow them.

For example, suppose you define a class in one module, and an extension function in another. Then you add the corresponding member function to the class and recompile its module (but not the other one). Neither of the compilation steps saw both functions, and so there was no chance to give an error.

Of course, this means that if the second module is recompiled later, it will give no errors but silently change the meaning (as member functions always take precedence over extension functions in Kotlin)… So maybe it’s preferable to give an error message then at least, even if it can’t always be given?

1 Like

I think this is exactly the point. If we recompile a library, but not the consumer, then it still uses the extension, behavior doesn’t change and this is expected. Maybe it would be a better design choice if the compiler fails when detected a member/extension clash.

1 Like