Extension functions in Kotlin are a way to add new behavior or functionality to an existing class without having to modify the class itself. They allow for concise and readable code by enabling developers to define methods that can be called on a particular type, even if that type was not originally designed to support those methods.
Extension functions are created by defining a function outside of a class or interface, but prefixing the function name with the class or interface type that it extends. When the function is called on an instance of that type, it behaves as if it were a member function of the class or interface.
Here is an example of an extension function for the ‘String‘ class:
fun String.isPalindrome(): Boolean {
val reversed = this.reversed()
return this == reversed
}
This extension function adds a ‘isPalindrome()‘ method to the ‘String‘ class, allowing us to check if a string is a palindrome. We can call the function on any instance of the ‘String‘ class, like this:
val palindrome = "racecar"
val notPalindrome = "hello"
println(palindrome.isPalindrome()) // true
println(notPalindrome.isPalindrome()) // false
In the above example, we create an extension function ‘isPalindrome‘ that utilizes the existing ‘reversed()‘ method to check if a ‘String‘ instance is a palindrome or not. By adding this extension function, we are able to call it on any ‘String‘ instance and receive a simple and reusable answer to whether or not the ‘String‘ is a palindrome.