0
0
Kotlinprogramming~5 mins

Extension function syntax in Kotlin

Choose your learning style9 modes available
Introduction
Extension functions let you add new actions to existing types without changing their code.
You want to add a new feature to a class from a library you can't change.
You want to make your code cleaner by adding helpful functions to common types.
You want to organize utility functions close to the types they work with.
You want to avoid subclassing just to add a small function.
You want to improve readability by calling functions directly on objects.
Syntax
Kotlin
fun ReceiverType.functionName(parameters): ReturnType {
    // function body
}
The ReceiverType is the type you are adding the function to.
Inside the function, you can use 'this' to refer to the receiver object.
Examples
Adds a 'shout' function to String that makes the text uppercase and adds an exclamation.
Kotlin
fun String.shout() = this.uppercase() + "!"
Adds 'isEven' function to Int to check if the number is even.
Kotlin
fun Int.isEven(): Boolean {
    return this % 2 == 0
}
Adds 'sumAll' to List of Ints to get the total sum.
Kotlin
fun List<Int>.sumAll(): Int = this.sum()
Sample Program
This program adds a 'shout' function to String and uses it to print 'HELLO!'.
Kotlin
fun String.shout() = this.uppercase() + "!"

fun main() {
    val word = "hello"
    println(word.shout())
}
OutputSuccess
Important Notes
Extension functions do not actually modify the original class; they are like helper functions.
If a member function and an extension function have the same signature, the member function is called.
You can define extension functions for any class, including your own or standard library classes.
Summary
Extension functions add new functions to existing types without changing them.
Use 'fun ReceiverType.functionName()' syntax to create them.
They help keep code clean and readable by adding useful functions directly to types.