Extension Function
Janak bista
Posted on September 15, 2022
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
}
Output : [3,2,1,4]
💖 💪 🙅 🚩
Janak bista
Posted on September 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
watercooler Why does a reboot make your PC run SO much faster than running all the cleaning tools you can possibly imagine?
November 30, 2024