ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
Kotlin Tutorial• 6 min read
Extension Functions: Enhancing Existing Classes
Adding methods to third-party or standard library classes without inheritance
Extension functions allow you to extend a class with new functionality without having to inherit from the class or use decorator patterns.
Writing Extension Functions
Prefix the function name with the receiver type: fun String.toSlug(): String.
Inside the extension function body, this refers to the receiver object instance.
Extensions do not actually modify the bytecode of the receiver class; they are resolved statically as static utility helper functions under the hood.
String and Date Extension Functions
// Extend the built-in String class with a custom formatting method
fun String.toTitleCase(): String {
return this.split(" ").joinToString(" ") { word ->
word.replaceFirstChar { it.uppercase() }
}
}
fun main() {
val title = "welcome to codexia android academy"
// Called as if it were a native method on String!
println(title.toTitleCase()) // Welcome To Codexia Android Academy
}Extension functions appear natively in IDE autocomplete.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
How does Kotlin implement Extension Functions under the hood on the JVM?