Kotlin Extension Function
Kotlin allows us to add new functions to existing classes, which is called Extension Function. This means we can add some functionality to the classes without having to inherit or modify them. In this tutorial, we'll discuss Kotlin Extension Function in detail.
Syntax
The syntax for declaring an extension function in Kotlin is as follows:
fun ClassName.functionName() {
// function body
}
Here, ClassName
is the name of the class to which you want to add a function, and functionName()
is the name of the function you want to add.
Example
Let's define an extension function called sum()
for the Int
class. The Int
class in Kotlin represents integer values.
fun Int.sum(n: Int): Int {
return this + n
}
In the example above, we define an extension function sum()
for the Int
class that takes an integer parameter and returns the sum of the integer value and the parameter.
Output
Now, we can call the extension function sum()
on an Int
object, just like a regular member function:
val num = 5
val result = num.sum(3)
println(result) // Output: 8
Explanation
In Kotlin, an extension function is a member function of a class that is defined outside the class. An extension function can be defined for a class, interface, or a nullable type. Once defined, the extension function can be called as if it were a member function of that class or interface.
Extension functions are useful for adding functionality to classes that are not under your control, such as Java or third-party classes. By providing extension functions, you can add new capabilities to these classes without modifying them.
Use
Kotlin extension functions can be used to:
- add functionality to existing classes that are not under your control
- simplify the code by providing utility functions that can be called on any object of a particular type.
Important points
- Extension functions can be defined for nullable types as well. In that case, you can check for null safety using the safe call operator '?'
- The visibility of an extension function is determined by the visibility of the package in which it's defined.
- The extension functions cannot override or access private members of the extended class.
Summary
In this tutorial, we discussed Kotlin Extension Functions, which allow us to add new functionality to classes without modifying or inheriting them. We covered the syntax, example, output, explanation, use and important points of Extension Functions in Kotlin. With this knowledge, you can now add extensions to existing classes, making your code more reusable and flexible.