0
0
Kotlinprogramming~5 mins

Extensions vs member functions priority in Kotlin

Choose your learning style9 modes available
Introduction
Sometimes you add new functions to existing classes without changing them. Kotlin lets you do this with extensions. But if a class already has a function with the same name, Kotlin uses the class's own function first.
You want to add a new function to a class you don't own or can't change.
You want to keep your code organized by adding helpers outside the class.
You want to avoid accidentally overriding existing class functions.
You want to understand why your extension function is not called when a member function exists.
Syntax
Kotlin
fun ClassName.extensionFunction() {
    // code here
}

// Member function inside the class
class ClassName {
    fun memberFunction() {
        // code here
    }
}
Extension functions are declared outside the class but look like member functions when called.
If a member function and an extension function have the same name and parameters, the member function is called.
Examples
The member function greet() is called because it has priority over the extension function.
Kotlin
class Example {
    fun greet() = "Hello from member"
}

fun Example.greet() = "Hello from extension"

fun main() {
    val e = Example()
    println(e.greet())
}
Since Example has no greet member function, the extension function greet() is called.
Kotlin
class Example {
    // No greet function here
}

fun Example.greet() = "Hello from extension"

fun main() {
    val e = Example()
    println(e.greet())
}
Sample Program
The Person class has a member function sayHello(). Even though there is an extension function with the same name, the member function is called because it has higher priority.
Kotlin
class Person(val name: String) {
    fun sayHello() = "Hello from member: $name"
}

fun Person.sayHello() = "Hello from extension: $name"

fun main() {
    val p = Person("Alice")
    println(p.sayHello())
}
OutputSuccess
Important Notes
Extension functions do not actually modify the class; they are static functions with receiver.
If you want to call the extension function when a member function exists, you must use a different name.
Extensions cannot override member functions.
Summary
Kotlin calls member functions before extension functions when names clash.
Extensions add new functions without changing the original class.
Use extensions to add helpers, but remember member functions have priority.