Extension Functions vs. Member Functions

Explore the key differences between extension functions and member functions.

Members and multiplicity

The biggest difference between members and extensions in terms of use is that extensions need to be imported separately. For this reason, they can be located in a different package. This fact is used when we cannot add a member ourselves. It is also used in projects designed to separate data and behavior. Properties with fields need to be located in a class, but methods can be located separately as long as they only access the public API of the class.

Multiple extensions with the same name

Thanks to the fact that extensions need to be imported, we can have many extensions with the same name for the same type. This is good because different libraries can provide extra methods without causing a conflict. On the other hand, it would be dangerous to have two extensions with the same name but different behaviors. If we have such a situation, it is a code smell and a clue that someone has abused the extension function capability.

Extensions are not virtual

Another significant difference is that extensions are not virtual, meaning that they cannot be redefined in derived classes. This is why if we have an extension defined on both a supertype and a subtype, the compiler decides which function is chosen based on how the variable is typed, not what its actual class is.

Get hands-on with 1200+ tech skills courses.