Kotlin by Example: Extension Functions
Adding functionality to existing classes with this sample code demonstrating extension function declaration on String class, extension property on Int, receiver object access with this keyword, and calling extensions like member functions.
Code
// Extend the String class with a new function
fun String.isPalindrome(): Boolean {
// 'this' refers to the string instance
val cleaned = this.lowercase().replace(Regex("\\s+"), "")
return cleaned == cleaned.reversed()
}
// Extend Int with a property
val Int.isEven: Boolean
get() = this % 2 == 0
fun main() {
val text = "Race car"
// Call it like a normal method
if (text.isPalindrome()) {
println("'$text' is a palindrome")
}
val num = 42
if (num.isEven) {
println("Even number")
}
}Explanation
Extension functions enable adding new functionality to existing classes without modifying their source code, inheriting from them, or using design patterns like Decorator. They are defined outside the class but can be called as if they were members of that class. This is particularly useful for extending third-party libraries or standard library classes like String or List that cannot be modified directly.
Extension functions are declared by prefixing the function name with the receiver type (the class being extended). Inside the extension function, the this keyword refers to the receiver object, the instance on which the function is called. While extension functions appear syntactically as member methods, they are resolved statically at compile time based on the declared type, not the runtime type.
Extension properties provide custom getters and setters accessible using dot notation without actually adding fields to the class. Since extensions cannot modify class memory layout, extension properties cannot have backing fields and must define custom accessors. Extensions do not break encapsulation as they cannot access private or protected members of the class they extend, only public API.
Code Breakdown
fun String.isPalindrome() extends String class with new function.this keyword refers to receiver object, the String instance.val Int.isEven extension property with custom getter, no backing field.text.isPalindrome() calls extension like member function.
