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 :

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 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 learnt about Kotlin Extension Functions with an example and also observed how an extension function is resolved during compile time.