Search code examples
extension-function

Unable to understand extension function in Kotlin Android?


I am not able to understand extension function and use it in my project. Can anyone guide me here please?


Solution

  • From the docs - “Kotlin provides the ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.”

    To understand this in an easy way, let’s consider the below example:

    First things first.

    Write 10 and then put a dot(.) after it and then try to write addTwoNumbers(). You’ll be getting errors at this stage as there is no property named addTwoNumbers() for an integer.

    Now, write this method:

    fun Int.addTwoNumbers(y: Int): Int = this.plus(y) //“this” corresponds to the integer number. (In this example, “this” refers to 10).
    

    Notice how we are using Int.addTwoNumbers().

    Let’s try to follow the same thing again:

    1. Write 10.

    2. Put a dot(.) after it.

    3. Try to write addTwoNumbers().

    4. And this time you’ll notice, it’s appearing as if this is the property of integer.

    Check the below code:

    fun main() {
        val sum = 10.addTwoNumbers(20) //here “this” will be assigned “10” and “y” will be assigned “20”
        println("sum: $sum")
    }
    

    This will print sum: 30 in the console.

    This phenomena is known as “Extension Function”.