Kotlin Extension Functions

Kotlin Extension Functions

Just as the name implies, “Extension functions” are extra functions that you apply to any object in your Kotlin code, it helps us to extend the functionality of objects without making any change to their code. Whether it’s a framework object like Buttons or Views, or it’s a custom object that you wrote yourself.

Extension functions basically help to organize your code to improve readability and reduce boilerplate. So, if you find yourself using a particular pattern over and over again in your code, it might be ideal to write an extension function and reduce the load.

Defining an extension function:

To define an extension function, just write a function as you normally would, then put the object name right before the function name, separated by a dot “.” like so:

fun Object.functionName(text: String){
//function body
}

Ideally, all your extension functions should be put away in another Kotlin file (doesn’t have to be a class), since the aim of writing them at first was to improve code readability and organization. Some examples of extension functions: A very simple use-case for extension functions would be Toast messages. Usually, you’d display toasts like this:

Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show()

And you’d have to call this everywhere you want to display toasts, so, if you have 50 fragments and you have to display toasts in each of them, you’d call this method 50 times over. Not so nice. To make it easier, we just write an extension function for all possible toasts in our app, like this:

fun Context.toast(toastMessage: String){
Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show()
}

Now we can easily call,

toast(toastMessage)

and we can do that in any activity or fragment in our app because it is now a function of the Context object.

Another (not so common) example, finding the percentage of an Integer, relative to another. In our extension file, we’d have a function like this:

fun Integer.findPercentage(number: Int): Double{
val percentage = (this/number).times(100)
return percentage 
}

Now, we can call 'findPercentage' on any integer in our application if need be.

Recap:

Extension functions can also be applied to more complex scenarios and they are really useful when it comes to code readability and organization. Mind you, there are some scenarios where you won’t need to use extension functions, it is important to learn when and when not to use them.

That’s it for this article, I hope you’ve learned a thing or two from it. Leave a comment if you’ve got any questions. Ciao!✌️