How to Create Extension Function in Kotlin: Simple Guide
In Kotlin, you create an extension function by prefixing the function name with the type you want to extend, like
fun String.yourFunction(). This lets you add new functions to existing classes without modifying their code.Syntax
An extension function is declared by writing fun, then the type you want to extend, followed by a dot and the function name. Inside the function, this refers to the receiver object.
- fun: keyword to declare a function
- TypeName.: the class you extend
- functionName(): your new function
- this: the instance of the extended type inside the function
kotlin
fun String.greet() {
println("Hello, $this!")
}Example
This example shows how to add a greet function to the String class. It prints a greeting message using the string value.
kotlin
fun String.greet() {
println("Hello, $this!")
}
fun main() {
val name = "Alice"
name.greet() // Calls the extension function
}Output
Hello, Alice!
Common Pitfalls
One common mistake is trying to override existing functions with extension functions; extensions do not replace member functions. Also, extension functions cannot access private members of the class. Another pitfall is forgetting that this inside the extension refers to the receiver object.
kotlin
class Person(val name: String) { fun greet() = println("Hi, I'm $name") } // Extension function with the same name fun Person.greet() = println("Hello from extension") fun main() { val p = Person("Bob") p.greet() // Calls member function, not extension }
Output
Hi, I'm Bob
Quick Reference
Remember these tips when creating extension functions:
- Use
fun TypeName.functionName()to declare. thisrefers to the receiver object.- Extensions cannot override existing member functions.
- They cannot access private or protected members.
- Useful for adding utility functions to existing classes.
Key Takeaways
Extension functions add new functions to existing classes without changing their code.
Declare them with fun, the type to extend, a dot, then the function name.
Inside the function, this refers to the object being extended.
Extension functions cannot override existing class member functions.
They cannot access private or protected members of the class.