Search code examples
kotlinkotlin-extension

Kotlin extension functions vs member functions?


I am aware that extension functions are used in Kotlin to extend the functionality of a class (for example, one from a library or API).

However, is there any advantage, in terms of code readability/structure, by using extension functions:

class Foo { ... }

fun Foo.bar() {
    // Some stuff
}

As opposed to member functions:

class Foo {

    ...

    fun bar() {
        // Some stuff
    }
}

?

Is there a recommended practice?


Solution

  • From my point of view, there are two compelling reasons to use extension functions:

    1. To "extend" the behaviour of a class you're not the author of / can't change (and where inheritance doesn't make sense or isn't possible).

    2. To provide a scope for particular functionality. For example, an extension function may be declared as a freestanding function, in which case it's usable everywhere. Or you may choose to declare it as a (private) member function of another class, in which case it's only usable from inside that class.

    It sounds like #1 isn't a concern in your case, so it's really more down to #2.