Extension Function in Kotlin

Extension Function:

An extension function is a function that adds new behaviour to a class, even if we don’t have access to the source code of that class. It’s a way to extend classes that lack some useful functions. In Java, this is usually implemented in utility classes which include a set of static methods.

Advantages of Extension Function in Kotlin:

The advantage of using extension functions in Kotlin is that we don’t need to pass the object as an argument. The extension function acts as part of the class, and we can implement it using this and all its public methods.

For instance, we can create a toast function that doesn’t need the context as a parameter, which could be used by any Context objects and those whose type extends Context, such as Activity or Service:

fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, duration).show()