Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 987
Farbod Salamat-Zadeh Avatar asked Nov 08 '17 13:11

Farbod Salamat-Zadeh


1 Answers

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.

like image 129
Oliver Charlesworth Avatar answered Oct 25 '22 11:10

Oliver Charlesworth