What is Extension Function in Kotlin: Simple Explanation and Example
extension function in Kotlin lets you add new functions to existing classes without changing their source code. It allows you to call these new functions as if they were part of the original class.How It Works
Imagine you have a toolbox (a class) but it doesn't have a tool you need. Instead of building a new toolbox, Kotlin lets you add that tool directly to your existing one. This is what an extension function does: it adds new abilities to a class without touching its original code.
Technically, an extension function is a regular function with a special receiver type. The receiver is the class you want to extend. When you call the extension function, Kotlin treats it as if it belongs to that class, so you can use it like a normal method.
Example
This example shows how to add a lastChar function to the String class that returns the last character of the string.
fun String.lastChar(): Char {
return this[this.length - 1]
}
fun main() {
val name = "Kotlin"
println(name.lastChar())
}When to Use
Use extension functions when you want to add useful features to classes you cannot modify, like classes from libraries or the Kotlin standard library. They help keep your code clean and readable by avoiding utility classes with static methods.
For example, you might add an extension function to format dates, manipulate strings, or simplify common tasks on collections. This makes your code easier to understand and maintain.
Key Points
- Extension functions let you add new functions to existing classes without inheritance.
- They are called like regular methods on the class instances.
- They do not actually modify the original class or its bytecode.
- Useful for adding helper functions to library or system classes.