Kotlin Extensions

Emre Arslan
Geek Culture
Published in
2 min readAug 27, 2021

--

Hello guys 👋🏻. In this article, I am going to explain one of the most powerful features in Kotlin, Extensions, and how to use them effectively in your projects. So let’s start 🚀

What is an Extension function?

Extension function is simply a function that you can add to any class and give this class a new behavior without inheriting it or making any internal changes. Also, this can be applied to a 3rd party library you use and whose source code is unknown.

Kotlin Extensions could be really handy and reduce the boilerplate code dramatically. Besides that, it improves your code readability.

Now, since at least we know what an extension is basically, let’s see it in action.

How to use Extensions?

Let’s start with writing our very first extension, shall we? 💪🏻

Imagine that, you will show or hide a view according to the response of an event. Normally, what you do is simply :

But there is a better and more elegant way to do it 💫. Let’s write an Extension function to View.

What we do here is that we have just added a new function to the View class. From now on, all view objects can use this function.

So the basic syntax for writing an extension is :

fun <Class Name>.<method name> { /* do the operation */ }

Let’s try another one. Toasts messages could be quite useful but every time using it as such could be quite annoying.

Toast.makeText(this, "My message", Toast.LENGTH_SHORT).show()

Let’s write a very basic toast extension to our activity so that we can use it in any activity we want with less code.

You can call it in any Activity as if it’s a member function of the activity.

Now, let’s try another one. This time we will set a URL to an ImageView via Glide. Normally, what we do is

Glide
.with(context)
.load("YOUR_URL")
.into(mImageView)

We can use an extension for that as well.

You can also use extensions to give a custom behavior to a member function. Let’s say you would like to prevent click spams and make sure the user can click the view only once. You can use an extension for that.

But first, we must create a class for this custom behavior.

Now we are ready to write our extension.

That’s all folks. You are now ready to use Kotlin Extensions 💯.

There are countless cases where extensions can be used. These are the most basic ones to start with 💪🏻.

As its name suggests extensions could be quite extended 😅.

Keep learning and happy coding 👨🏼‍💻👩🏼‍💻.

--

--