Kotlin: Power of Extension functions

Ravi Mishra
2 min readFeb 19, 2022

I had started android development with java. To write a utility function I had to write in a util class as a singleton. This function also doesn’t appear in autocomplete.

Although it worked well for me. But then I learned about extensions in Kotlin. I was amazed and adopted it immediately.

What are extension functions?

According to the Kotlin 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.

Basically, with an extension, we can extend and write our own functions for classes like an activity, fragment, data class or any other Kotlin class in general.

Let’s take an example to understand how we can use extensions. Suppose we need to show Toast in our activity.

With our extension function toast(), we can display a toast without the need of passing the context and duration. Similarly, for showing long toast you can create a new function longToast() and use it across the activities.

Let’s discuss other important uses cases of extensions.

EditText Validation

A useful use case is a validation. You can create functions to validate phone, email, username etc. Code snippet for validation:

Here default regex functions are used to check the validation of phone and email. If the string doesn’t match the criteria for phone or email, an error warning will be displayed in the respective edit text.

Updating visibility of views

We vary often need to change the visibility of our views. We can reduce the effort in doing so by using extensions. Here is the code snippet for updating the visibility.

Loading image in ImageView

The effort in loading images in image view could also be reduced using extensions. In the following snippet, I've demonstrated how you can load images in image view using popular libraries like Glide and Picasso.

These are a few examples of how you can employ extension functions to ease your development. Now that you have the idea how the extensions works, you can write your own functions for different scenarios and use cases.

Thanks!

Happy Coding!!

--

--