Extension Functions in Kotlin

What are Extension Functions in Kotlin

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

Syntax for Extension Function in Kotlin :

Following is the syntax to define an extension function for a class.

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

Let us understand the extension functions in Kotlin with the below example :

Output :
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 nut shell, 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.

Find official reference to extension functions at https://kotlinlang.org/docs/reference/extensions.html

Conclusion :

In this Kotlin Tutorial, we have learnt about extension functions in Kotlin with an example and also observed how an extension function is resolved during compile time.