Extension functions let you add new actions to existing classes without changing their code. This helps keep your code clean and easy to read.
0
0
Extension functions in Android Kotlin
Introduction
You want to add a helper function to a class from a library you can't change.
You want to make your code more readable by adding meaningful functions to common types.
You want to organize utility functions close to the types they work with.
You want to avoid creating subclasses just to add small functions.
You want to keep your code simple and avoid cluttering classes with extra methods.
Syntax
Android Kotlin
fun ClassName.newFunctionName(params): ReturnType {
// function body
}Use the keyword
fun followed by the class name you want to extend.Inside the function,
this refers to the instance of the class.Examples
Adds an exclamation mark to any String.
Android Kotlin
fun String.addExclamation(): String {
return this + "!"
}Checks if an integer is even.
Android Kotlin
fun Int.isEven(): Boolean {
return this % 2 == 0
}Calculates the sum of all integers in a list.
Android Kotlin
fun List<Int>.sumAll(): Int {
var sum = 0
for (num in this) {
sum += num
}
return sum
}Sample App
This program adds a shout function to the String class. It makes the text uppercase and adds an exclamation mark. Then it prints the shouted greeting.
Android Kotlin
fun String.shout(): String {
return this.uppercase() + "!"
}
fun main() {
val greeting = "hello"
println(greeting.shout())
}OutputSuccess
Important Notes
Extension functions do not actually modify the original class; they just look like they do.
If a class already has a function with the same name and parameters, the class's own function is called instead of the extension.
Use extension functions to keep your code organized and easy to understand.
Summary
Extension functions add new functions to existing classes without changing them.
They make your code cleaner and easier to read.
You can call them like regular functions on the class instances.