Extension functions in Kotlin

Extension functions in Kotlin

Kotlin is an amazing programming language that brings a plethora of powerful features to developers. One standout feature is Extension Functions, which allow you to extend the functionality of existing classes without modifying their source code or inheriting from them.

Imagine adding your custom methods to predefined classes like Int, String, or List—this is exactly what extension functions enable! Let’s explore this concept with a practical example: determining whether a number is prime.


Without Extension Functions

Here’s how we would traditionally write a function to check if a number is prime:

fun main() {
    val x: Int = 20
    val y: Int = 11

    if (isPrimeNum(x)) {
        println("x is a prime number")
    } else {
        println("x is not a prime number")
    }

    if (isPrimeNum(y)) {
        println("y is a prime number")
    } else {
        println("y is not a prime number")
    }
}

fun isPrimeNum(num: Int): Boolean {
    for (i in 2 until num) {
        if (num % i == 0) {
            return false
        }
    }
    return true
}        

In this code

  • We define a standalone function isPrimeNum(num: Int).
  • To check if a number is prime, we pass the number as an argument to the function.
  • The syntax is verbose and doesn't feel intuitive.


With Extension Functions

fun main() {
    val x: Int = 3
    val y: Int = 12

    if (x.isPrimeNum()) {
        println("x is a prime number")
    } else {
        println("x is not a prime number")
    }

    if (y.isPrimeNum()) {
        println("y is a prime number")
    } else {
        println("y is not a prime number")
    }
}

fun Int.isPrimeNum(): Boolean {
    for (i in 2 until this) {
        if (this % i == 0) {
            return false
        }
    }
    return true
}        

In this code

  • The extension function isPrimeNum() is directly defined on the Int class.
  • We use this within the extension function to refer to the calling object.
  • The function can now be called on any integer directly, making the code more concise and natural.


Some amazing things about the Extension function

  • Extension functions allow you to add new functionality to a class without inheriting from or modifying the original class.
  • If the original class has the same method name as the extension function then it will go with a method that is defined in the class:

like for example

class Base {
    fun welcomeUser() {
        println("Hello User") // This will be executed
    }
}

// Extension Function
fun Base.welcomeUser() {
    println("Welcome User") // This will not be executed
}

fun main() {
    val base = Base()
    base.welcomeUser() // Output: "Hello User"
}        

This happens because extension functions are resolved statically (at compile time), while class methods are resolved dynamically (at runtime). During compile time, the binary code is generated for both the class method and the extension function. However, at runtime, the class method is prioritized because it is part of the class's intrinsic behavior.

To put it simply, imagine you have a main notebook and a sticky note. If both have content under the same title, you will naturally prioritize the content in the main notebook over the sticky note. Similarly, the program gives preference to the class method over the extension function when they share the same name.

  • Now in one other case if the extension function and class's function name same but accept different values then it call depends on what value you pass in the function for example:

class Base {
    fun welcomeUser() {
        println("Hello User") // This will be executed
    }
}

// Extension Function
fun Base.welcomeUser(name: String) {
    println("Welcome $name") // This will not be executed
}

fun main() {
    val base = Base()
    base.welcomeUser() // Output: "Hello User"
   base.welcomeUser("Suresh") // Output: "Welcome Suresh"
}        

Why does this run because during compiling byte code is generated in both cases but in this case, extension functions to overload member functions that have the same name but a different signature


for more learning read : https://kotlinlang.org/docs/extensions.html


Conclusion

In conclusion, extension functions are a great way to enhance predefined classes, allowing you to add functionality that can be easily accessed throughout the entire project.

要查看或添加评论,请登录

Henil Chhipani的更多文章

社区洞察

其他会员也浏览了