Extension Functions in Kotlin
Introduction
Extension Functions is a fundamental concept every Kotlin developer should understand. Extension functions add methods to existing classes without inheritance — a core Kotlin idiom used throughout the standard library.
Extension functions add new behaviour to existing types without modifying their source. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Extension functions add new behaviour to existing types without modifying their source.
- They are resolved statically based on the declared receiver type.
- The Kotlin standard library uses extensions extensively for strings and collections.
Syntax
fun String.lastChar(): Char = this[this.length - 1]Extension Functions in Kotlin Example Program in Kotlin
fun String.lastChar(): Char = this[this.length - 1]
fun Int.isPositive() = this > 0
fun main() {
val text = "Kotlin"
println("Last char of $text is ${text.lastChar()}")
println("Is 10 positive? ${10.isPositive()}")
}Sample Output
Last char of Kotlin is n
Is 10 positive? trueWhen to use
Use extensions to add domain-specific helpers to String, List, or third-party types you cannot modify.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
Extension functions add new behaviour to existing types without modifying their source.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- Extension functions add new behaviour to existing types without modifying their source.
- They are resolved statically based on the declared receiver type.
- The Kotlin standard library uses extensions extensively for strings and collections.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.