Kotlin Extension Function: In this tutorial, you will learn to extend a class with new usefulness using extension functions.
Assume, you need to extend a class with new functionalities. In most programming languages, you either derive a new class or uses some sort of design example to do this.
In any case, in Koltin, you can likewise use the extension function to extend a class with new functionalities. Fundamentally, an extension function is a member function of a class that is characterized outside the class.
For instance, you need to use a technique to the String class that returns a new string with the first and last character eliminated; this strategy isn’t as of now accessible in String class. You can use the extension function to achieve this assignment.
What is the definition of Extension Function??
Essentially, an extension function is a member function of a class, which is characterized outside the class. For example, on the off chance that you need to use a strategy to the String class that returns a new string with the first and last character eliminated, you can write an extension technique for it. In fact, this technique isn’t as of now accessible in String class.
Example: Remove First and Last Character of String
fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1) fun main(args: Array<String>) { val myString= "Hello Everyone" val result = myString.removeFirstLastChar() println("First character is: $result") }
At the point when you run the program, the output will be:
First character is: ello Everyon
Here, an extension function removeFirstLastChar() is added to the String class.
The class name is the recipient type (String class in our example). The this catchphrase inside the extension function refers to the recipient object.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.