DEV Community

Janak  bista
Janak bista

Posted on

Extension Function

Kotlin gives the programmer the ability to add more functionality to the existing classes, without inheriting them.

This is achieved through a feature known as extensions.

When a function is added to an existing class it is known as Extension Function.

To add an extension function to a class, define a new function appended to the class name.

For Example :

fun main() {
 val list = mutableListOf(1,2,3,4)
 list.swap(0,2)
 print(list)
}
fun MutableList<Int>.swap(index1: Int, index2: Int) {
    val tmp = this[index1] // 'this' corresponds to the list
    this[index1] = this[index2]
    this[index2] = tmp

}
Enter fullscreen mode Exit fullscreen mode

Output : [3,2,1,4]

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay