How the Kotlin extension makes my work easy and clean code!!!

Ashiqul Islam Shaon
2 min readNov 14, 2020

I started coding using Kotlin almost 2 years ago. It is a long journey and I love Kotlin. I almost forgot what it feels like to coding in Java.

We had written code using java and we solved many problems. But how Kotlin Extension makes our works even easier?

Let’s talk about how it makes my work easier. I have created a repository containing some extension that I used in my project. I will explain some of this.

What is Kotlin Extension?

In a class, you need some functions or some properties that this class doesn’t provide. So you can create your own methods or field associated with the class without inheriting any class. This is called Kotlin Extension. Then you can call them within the class.

If I create a field or function associated with the String class then I can call them where I use the string class.

fun <T> AppCompatActivity.startActivityNormally(to: Class<T>, extras: Bundle.() -> Unit = {}) =
startActivity(Intent(this, to).apply {
putExtras(Bundle().apply(extras))
})

Let’s talk about the above extension function. It helps me to write simple code and reduces my line of code to achieve my goal.

startActivityNormally(ActivityName::class.java)

Calling this will start an activity. If I need to pass extra data in intent, I can also do this easily.

startActivityNormally(ActivityName::class.java) {
putSerializable("post", data as Serializable)
putString("id", data.id)
putString("name", data.name)
}

Isn’t it beautiful? yeah, it is!

Let’s see more…..

If I need to do validation on a mobile number. I can do it easily by calling the below function.

fun String.isMobileValid(): Boolean {
if (!this.isNullOrEmpty() && this.length == 11) {
val prefix = this.substring(0, 3)
return prefix == "017" || prefix == "016" || prefix == "018" || prefix == "015" || prefix == "019" || prefix == "013" || prefix == "014"
}
return false
}

Here is how to call the extension function

val mobile = "01521401596"
if (!mobile.isMobileValid()) {
_toast.value = "Mobile is not valid"

return false
}

--

--