Why Kotlin extension is preferable to use in android project

Sharing is caring!

As android developers, We are a writing lot of code to make an awesome application. We all know that Android uses Java as a language. In application development, we used many java concepts like thread, singleton classes, etc without knowing the android concept. It may cause memory leaks in Android. I remembered that we have used a lot of boilerplate code in our project, one of them is very popular findViewById(). Now the Google realised that Server-side Java code is not a good fit for android development because android architecture works in a different pattern.

So here Google officially launched the Kotlin is the new primary language a year ago for Android development. The Android community has already welcomed a new programming language in android application development because of its good response and much easier to write the code because it has the similarity of Java API. Kotlin community working hard to make a lot of plugins for Kotlin which makes it easier for a developer to write the code in all patterns. So in this tutorial, we are going to talk about the much-used plugin named Kotlin-Android-extensions.

Start using Kotlin Android Extensions:

Kotlin-android-extensions is now good supported by android studio.

As per the official document

Extensions do not modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.

It means it is just like a static function that can be extended to any other class to use. Another reason for using the extension function is, you don’t have to extend that class to use the methods as if they belong to that class (but not actually part of that class).

Kotlin has provided the plugin to start using in android to extend the functionality of the existing Android API. You need to just add the below plugin as an extension.

apply plugin: 'kotlin-android-extensions'

That’s it. Generally, in android, we are making view visibility and invisibility in many places. We are checking the particular view is visible or not. If it is visible then make this view gone or invisible and vice versa.  In this case, we can create a ViewExtention.kt file to write an extended function to use many places if required. Let’s see an example of check view is visible or not and make then visible and invisible as per requirement.

 

fun View.visible() {
    this.visibility = View.VISIBLE
}

fun View.visible(visible: Boolean) {
    if (visible) {
        visible()
    } else {
        gone()
    }
}

fun View.gone() {
    this.visibility = View.GONE
}

fun View.invisible() {
    this.visibility = View.INVISIBLE
}

fun View.isVisible(): Boolean {
    return visibility == View.VISIBLE
}

fun View.isGone(): Boolean {
    return visibility == View.GONE
}

fun View.isInvisible(): Boolean {
    return visibility == View.INVISIBLE
}

As I remember we used a snack bar to show a message to users like success or error for API call. So we can create an extension function of a snack bar to call multiple places. The best benefit is that we can directly excess this extension function to any Class without using the name of Class.

fun View.snackbar(resId: Int, duration: Int = Snackbar.LENGTH_SHORT) {
    snackbar(this.resources.getString(resId), duration)
}

fun View.snackbar(msg: String, duration: Int = Snackbar.LENGTH_SHORT) {
    Snackbar.make(this, msg, duration).show()
}

fun View.longSnackbar(resId: Int) {
    snackbar(resId, Snackbar.LENGTH_LONG)
}

It is very simple to call in your View Class.

viewError.visible()
            
 textViewError.snackbar("error")

The extension features are not only View Class, but we can also use any Android or Kotlin class or any architecture level like ViewModel. Let’s see an example of loading a list of data in recycler view via API call, So we want to observe MutableLiveData source with the help of LifeCycleOwner to monitor the life cycle change. For that, we can create an extension function that observes the change of Object into a Fragment. Let’s see an example of ViewModelExtention.kt.

fun <T> BaseViewLifecycleFragment.observe(data: MutableLiveData<T>, function: (data: T?) -> Unit) {
    getViewLifecycleOwner1()?.let{
        data.observe(it, android.arch.lifecycle.Observer {
            function(it)
        })
    }
}

We can call this function in our View class to observe the change of MutableLiveData which we have defined in the ViewModel to load the data on the RecyclerView adapter.

  observe(viewModel.movieList, {
            it?.let {
                adapter.dataList = it
            }
            showNoDataFound(adapter.dataList.isEmpty())
        })

You can make many more extension functions with existing Class to add any other function without inheriting. It can access in any class without using the Class Name. We can write much cleaner code to our project like not to use boilerplate code findViewById. We can use the extensions feature to remove this. It is much compatible with any architectural level design like MVVM with Koin dependency Injection and Coroutine for async background calls.

Wrapping 

Now we have a good understanding of the Koin Android extension feature. You can get the complete Github source code of Kotlin MVVM architecture design with Koin and Coroutine. In my next tutorial, we will learn a few more technical stuff, till then enjoy your healthy day.

If you are wondering to learn Android then Please learn from the Android category and wondering to learn Kotlin then Kotlin Category will help you. If you want to learn all the python articles, then learn from the python category.

Please do subscribe to your email to get the newsletter on this blog below and if you like this post then do not forget to share like and comment on the below section.

Happy Coding 🙂

0 0 votes
Article Rating
Why Kotlin extension is preferable to use in android project
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Scroll to top
0
Would love your thoughts, please comment.x
()
x