How and When to convert a Utility function in Kotlin to an Extension Function

BHAVNA THACKER
3 min readFeb 15, 2022

--

Kotlin comes with this awesome feature of Extension Functions and Developers working in Kotlin are encouraged to use this feature!

“Kotlin Extension Functions” By Bhavna Thacker

If you like to learn by watching videos, then here is the link to the same at my youtube channel:

https://www.youtube.com/watch?v=KCcVW5JXj60

First of all, let’s see/revise what is an Extension function from official documentation:

“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.

For example, you can write new functions for a class from a third-party library that you can’t modify. Such functions can be called in the usual way, as if they were methods of the original class. This mechanism is called an extension function. There are also extension properties that let you define new properties for existing classes.”

Now let’s look at How does an Extension function look like from official documentation:

fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}

The this keyword inside an extension function corresponds to the receiver object (the one that is passed before the dot). Now, you can call such a function on any MutableList<Int> from official documentation:

val list = mutableListOf(1, 2, 3)
list.swap(0, 2) // 'this' inside 'swap()' will hold the value of 'list'

Now time for some real time scenarios. While working in a real world app, you often come across data in the form of “Date” coming from remote servers/local DB, which you have to format before displaying it in UI and there comes the need to FORMAT it. So, you may write a Utility function like this below in a kotlin file say Utils.kt:

fun formatToString(date: Date): String {
val format = SimpleDateFormat(“EEE, d MMM yyyy”, Locale.getDefault())
return format.format(date)
}

And you access this function like below passing it a Date(e.g. task.deadline):

val text = formatToString(task.deadline)

Here you see the opportunity to create an Extension Function on Date class. Instead of passing date as a parameter, why not create an Extension function on Date class as below:

fun Date.formatToString(): String {
val format = SimpleDateFormat("EEE, d MMM yyyy", Locale.getDefault())
return format.format(this)
}

Notice, three important changes. Function now starts with Date.something(), date is no longer passed as a parameter and it is accessed using this

Now to access the function, you would modify the call and it will look like below:

val text = task.deadline.formatToString()

So Simple when it comes to Creating and Using Extension function!

In your app, if you notice that you have several utility functions — all working on a Date or View etc., you could just convert them like above and put them in one File named DateExtensions.kt or ViewExtensions.kt.

Here is my Utils.kt (Before):

import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
fun formatToString(date: Date): String {
val format = SimpleDateFormat(“EEE, d MMM yyyy”, Locale.getDefault())
return format.format(date)
}
fun getDateWithoutTime(date: Date): Date {
try {
val formatter = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
return formatter.parse(formatter.format(date)) ?: date
} catch (e: Exception) {
}
return date
}

Here is my DateExtensions.kt (After):

import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*

fun Date.formatToString(): String {
val format = SimpleDateFormat("EEE, d MMM yyyy", Locale.getDefault())
return format.format(this)
}


fun Date.getDateWithoutTime(): Date {
try {
val formatter = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
return formatter.parse(formatter.format(this)) ?: this
} catch (e: Exception) {
}
return this
}

That’s it folks about Kotlin Extension functions!

Hope you enjoyed reading this and you will keep an eye on such opportunities to create and use them in Kotlin. Please leave a Clap if you liked it!

--

--

BHAVNA THACKER

Android GDE. Youtuber — LearnAndroid. Senior Android Engineer @MEGA. FPE @raywenderlich.