0
0
KotlinConceptBeginner · 3 min read

What is Extension Function in Kotlin: Simple Explanation and Example

An 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.

kotlin
fun String.lastChar(): Char {
    return this[this.length - 1]
}

fun main() {
    val name = "Kotlin"
    println(name.lastChar())
}
Output
n
🎯

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.

Key Takeaways

Extension functions add new behavior to classes without changing their code.
They are called as if they are part of the original class.
Use them to keep code clean and add helpers to classes you can't edit.
They do not alter the original class but provide a convenient syntax.
Great for enhancing library or built-in classes with custom functions.