Kotlin Extension Functions

Kotlin Extension Functions are a way of extending the abilities of a class. Kotlin Extensions help in adding functions to a class without actually inheriting the class.

Syntax for Kotlin Extension Function

The syntax to define an extension function for a class is

</>
Copy
fun ClassType.function_name (Parameters): ReturnTypeIfAny{
     // body of the function
}

Let us understand the extension functions in Kotlin with the following example.

example.kt

</>
Copy
import java.io.File

/**
 * Created by www.tutorialkart.com
 */

class Calculator{
    fun add(a: Int, b: Int): Int{
        return a+b
    }

    fun subtract(a: Int, b: Int): Int{
        return a-b
    }
}

fun main(args: Array) {
    var a=8
    var b=6
    var calc:Calculator = Calculator()
    println(calc.add(a,b))
    println(calc.subtract(a,b))
    println(calc.multiply(a,b))
}
// multiply is an extension function to the class Calculator
fun Calculator.multiply(a: Int, b: Int): Int{
    return a*b
}

Output

14
2
48

In the above program, Calculator class is having two functions namely add, subtract. Using extensions in Kotlin, we have added a new function, namely multiplication, to the Calculator class.

Adding an extension function does not affect the original class, ie., Calculator class.

How are extension functions resolved? – Statically

Extension functions are resolved during compile time based on the type of object we are calling the function upon,  i.e., in the above example, we have created an object calc of type Calculator, and called multiply function using calc.multiply. As we have already declared calc of type Calculator, compiler checks if there is an extension function called multiply for the class type of calc, i.e., Calculator.

In a nutshell, extension functions are being called based on the type of expression (here its calc in the example), and not by the type of value that expression consolidates to.

Conclusion

In this Kotlin Tutorial, we have learned about Kotlin Extension Functions with an example and also observed how an extension function is resolved during compile time.