Effective Kotlin Item 46: Avoid member extensions
When we define an extension function to some class, it is not added to this class as a member. An extension function is just a different kind of function that we call on the first argument that is there, called a receiver. Under the hood, extension functions are compiled to normal functions, and the receiver is placed as the first parameter. For instance, the following function:
Under the hood is compiled to a function similar to this one:
One of the consequences of how they are implemented is that we can have member extensions or even define extensions in interfaces:
Even though it is possible, there are good reasons to avoid defining member extensions (except for DSLs). Especially, do not define extension as members just to restrict visibility.
One big reason is that it does not really restrict visibility. It only makes it more complicated to use the extension function, since the user would need to provide both the extension and dispatch receivers:
You should restrict an extension visibility using a visibility modifier, not by making it a member.
If you need a function to be a member, for instance when it needs to use class state, and you want to call it like an extension, consider using
Why avoiding extension functions?
There are a few good reasons why we prefer to avoid member extensions:
- Reference is not supported:
- Implicit access to both receivers might be confusing:
- When we expect an extension to modify or reference a receiver, it is not clear if we modify the extension receiver or dispatch receiver (the class in which the extension is defined):
- For less experienced developers it might be counterintuitive or scary to see member extensions.
Avoid, not prohibit
This rule does not apply everywhere. The most obvious situation where member extensions need to be used, is when we define DSL builders (as presented in the Item 35: Consider defining a DSL for complex object creation). Member extensions are also useful when we need to define a function that is called on some scope. One example might be a member function producing a
produce. Another might be an integration test function calling an endpoint on
TestApplicationEngine, and defined in an interface (as I explained in my article Traits for testing in Kotlin, this is a popular pattern used on backend integration tests). In both cases defining this function as a scope is not our whim, but serves a concrete purpose.
We prefer to avoid member extensions, but we use them, if they are the best option we have.
To summarize, if there is a good reason to use a member extension, it is fine. Just be aware of the downsides and generally try to avoid it. To restrict visibility, use visibility modifiers. Just placing an extension in a class does not limit its use from outside.