What if your new function never runs because the original one silently takes priority?
Extensions vs member functions priority in Kotlin - When to Use Which
Imagine you have a class with some functions, and you want to add new behavior without changing the original class code. You try to add extra functions outside the class, but sometimes the program doesn't use your new functions as you expected.
Manually guessing which function will run--your added one or the original--can be confusing and cause bugs. You might waste time debugging why your new code is ignored, especially when both have the same name.
Kotlin's rule that member functions always have priority over extension functions clears this confusion. It helps you know exactly which function will run, making your code predictable and easier to maintain.
fun String.print() { println("Extension") } class Example { fun print() { println("Member") } } Example().print()
class Example { fun print() { println("Member") } } fun Example.print() { println("Extension") } Example().print()
This rule lets you safely add new functions to classes without accidentally overriding existing behavior, making your code clearer and more reliable.
When working with a library class you cannot change, you can add helpful functions as extensions. Knowing member functions have priority prevents unexpected behavior when the library updates its own functions.
Member functions always run before extension functions if both have the same name.
This rule avoids confusion and bugs when adding new functions to existing classes.
It helps keep your code predictable and easier to maintain.