How to Use Extension Functions in Android with Kotlin
In Kotlin for Android, you use
extension functions to add new functions to existing classes without changing their source code. Define an extension function by prefixing the function name with the class name followed by a dot, like fun String.myFunction(), then call it on any instance of that class.Syntax
An extension function is declared by writing fun, then the class name you want to extend, a dot, and the function name. Inside the function, this refers to the instance of the class.
- fun: keyword to declare a function
- ClassName.: the class you want to add the function to
- functionName(): your new function
- function body: code that runs when you call the function
kotlin
fun String.addExclamation(): String {
return this + "!"
}Example
This example shows how to create an extension function for the String class that adds an exclamation mark at the end. Then it calls this function on a string.
kotlin
fun String.addExclamation(): String {
return this + "!"
}
fun main() {
val greeting = "Hello"
println(greeting.addExclamation())
}Output
Hello!
Common Pitfalls
One common mistake is trying to override existing functions with extension functions; extensions do not replace class methods. Also, extension functions cannot access private members of the class. Another pitfall is forgetting that this inside an extension refers to the receiver object.
kotlin
class Person(val name: String) { fun greet() = "Hi, $name" } // Extension function with same name - does NOT override fun Person.greet() = "Hello, $name" fun main() { val p = Person("Anna") println(p.greet()) // Calls original greet(), not extension }
Output
Hi, Anna
Quick Reference
- Use
fun ClassName.functionName()to declare an extension. - Call the extension like a normal method on the class instance.
- Extensions cannot override existing class methods.
- Extensions cannot access private or protected members.
- Use extensions to keep code clean and add utility functions.
Key Takeaways
Extension functions add new behavior to existing classes without inheritance.
Declare extensions with fun ClassName.functionName() syntax.
Extensions cannot override existing class methods or access private members.
Call extension functions like regular methods on class instances.
Use extensions to write cleaner and more readable Android Kotlin code.