Kotlin Extension Function

Updated 28 April 2022

Save

In this blog, we going to discuss the Kotlin Extension Function.

When we want to add any extra function to the class with the existing functionality then the inheritance comes to mind. We inherit that existing class and add the new functionality in the child class.

Kotlin supports the extension function which will allow extending the existing class functionality without inheritance. We simply add the new method to the existing class just with the help of the class name and can access that method easily.

Create extension function

We can create the extension function in kotlin like a normal function only we have added the class name just before the function name Activity.showCustomAlert()

Inside our extension function, we have displayed the alert dialog with the details that we have received on the extension function parameters.

Here the context is basically the activity context. In my case, I am using BaseActivity as the activity name so you can add your own activity.

Then the next, we have the title and content or message of the alert. Cancelable param is used for setting the alert as cancelable or noncancelable if you ignore to pass the value at the function call time it will set the default value as true.

Next, we are passing the positive and negative button text and the click listener functionality. It will also be used as null by default if we did not pass any.

Accessing extension function

We have added this new extension function inside the activity class now we can access the method anywhere in our class.

Conclusion:

In this blog, we have learned about the implementation of the Kotlin Extension Function.

For more information regarding the Kotlin Extension Function follow the link.

Thanks for reading this blog. You can also check other blogs from here.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home