In this tutorial you will learn about the Kotlin Extension Function and its application with practical example.
Kotlin Extension Function
In Kotlin We can use extension function to extend class. In Most of the programming langauge we have to create derived class to do this. The Extension Function is declared outside the class and is a member function of class.
Example: Let’s get understand it by an example, In below example we are going to remove first two word from string. Check below code
1 2 3 4 5 6 7 |
fun String.removeFirstTwoChar(): String = this.substring(2, this.length) fun main(args: Array<String>) { val str_my= "Welcome to W3Adda" val result = str_my.removeFirstTwoChar() println("Result is: $result") } |
In aboce code removeFirstTwoChar() is an extension function which is added to the String class.
String class is receiver type and the this keyword inside the extension function is receiver object.
Output: So here is the output.