Photo by Caspar Camille Rubin on Unsplash

Kotlin : Extension Function

Kiran Pande
2 min readJun 27, 2020

--

We use multiple classes for creating objects and using its properties. These classes are sometimes in-scope of developer, means we can modify or extend class definition as per new requirements. But, they are some classes where we have no control to even look into it. Library classes are not in scope of modification. While, Final classes are not in scope of inheritance. For Example, String class can neither be modified nor extended.

So, Kotlin provides mechanism of “Extension Function” to add more features to existing class. It will act same as member function, but it will NOT be a part of existing class. There are also extension properties that let you define new properties for existing classes.

Now, consider above Person class, which is Final by default. (In Kotlin, all classes are Final by default). It provides two separate method to print FirstName and LastName. But, there is a new requirement which will print both names combined and may have some prefix to it. To achieve this using “Extensions” we can write new function in desired application and add receiver of Person class.

Member Functions

If there is already present a member function which has same name and same receiver as extension function, then member function wins.

But, extension function can overload existing member function by different method signature.

Null Safety

Extension method can be implemented using nullable type. These methods will be STILL executed, even if variable is NULL. Below code allows you to call extension function in Kotlin without checking for null. Check happens inside the extension function.

Thank You :)

--

--