Kotlin Extensions as your friend

Kotlin Extensions as your friend

Hello, dev!

If you are a newbie Android developer like me or somebody who is switching from good old Java to something refreshing like Kotlin, I strongly recommend you to use Kotlin extension functions to make your code more readable and more organized by extracting even the simplest business logic from the UI.

What are extensions in Kotlin?

Extensions will allow you to extend the functionality of some class without inheriting it or using some design pattern. The best way is to show some examples from Android.

Let's assume that we depend on the Context for some functions like hiding a soft keyboard.

/**
 * Hides keyboard for a given view.
 */
fun Context.hideKeyboard(view:View) {
    val inputManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    inputManager.hideSoftInputFromWindow(view.windowToken, 0)
}

In order to get the system service through context, we need to call it in the Activity, Fragment, or some other class which we must provide context from the outside. With extensions functions, we can easily create a separate file and extend Context functionality so we can use our context without any issues. And then we can call this function in our needed Activity or Fragment.

Here is another simple example to wrap the big picture.

Sometimes we need some views to be visible or gone in our UI so we can get better UX for our users. Again, extensions come in handy to extract as much logic from the UI parts of your app.

Instead of setting the visibility of your progress bar like this:

progressBar.visibility = View.VISIBLE

You can separate the logic in the Kotlin file called ViewExtensions.kt and then simply write this:

/**
 * Sets visibility to visible
 */
fun View.show() {
    visibility = View.VISIBLE
}

/**
 * Sets visibility to invisible
 */
fun View.hide() {
    visibility = View.GONE
}

and then in Fragment call the extension in a more readable way

progressBar.show()

progressBar.hide()

Do you need some validation logic? No problem.

fun String.isValidAge(): Boolean {
        val age : Int = this.trim().toInt()
        if(age in 18..40) {
            return true
        } 
  return false
}

And in your UI part

submitButton.setOnClickListener {
if(ageInputText.isValidAge()) {
         submitForm()
      } else {
         showToast()
      } 
}

This is small fraction of how useful this things can be. For larger projects, Kotlin extensions are your friend, and try to use them to clean your code as much as possible. Feel free to use them in ViewModels, Activities, Fragments, or some other classes as well. Code readability will increase a lot, and I mean a looooot!

Thanks for reading my first blog post. Follow me for more regular posts and happy coding!