It is very common that you log messages while developing an Android app. And you must be writing below code all the time in each of your activity.
private static final String TAG = "MyActivity"; // Or private static final String TAG = YouActivity.class.getName(); Log.d(TAG, "Your message goes here");
Right? So now in Kotlin, We can take advantage of extension function to remove TAG from each activity and have it once in extension function.
Extension functions allow us to extend the functionality of classes without having to touch its code. So now we can extend Activity to create our own function. In this case, We will extend it to log messages.
Create Extension.kt file under util package and write the below code in it.
fun Activity.logd(message: String){
if (BuildConfig.DEBUG
) Log.d(this::class.java.simpleName, message) }
To create an extension function, put the name of the class that you want to extend then put a dot (.) and then name of your function. In the above code, we are creating the extension function for Activity that will log the messages. And, that’s it! We created an extension function.
Just call our very own created extension function from any activity. No need to create and pass TAG like before. Just write this.
logd("Fab button clicked")
With an extension function, you can extend and create your own function even if you don’t have access to the code. There are lots of possible uses of the extension function. Consider a case where you want a little modification in the library that you are using.
You can also create extension function to display toast in activity instead of writing in each of your activity like this
Toast.makeText(this, "Display toast", Toast.LENGTH_SHORT).show();
You can just create extension function such as
fun Activity.toast(message: String){ Toast.makeText(this, message , Toast.LENGTH_SHORT).show(); }
And call it from any activity as
toast("Display toast")
Awesome, right? Seems like giving super powers to existing functions in the class.
And that is all! Feedback appreciated. Thanks!
Learn more about extension function here. Also read: Dart or Kotlin: Selecting the Perfect Language for Your App Development