Google News
logo
Kotlin - Interview Questions
What are extension functions in Kotlin?
Extension functions in Kotlin allow you to add new functions to existing classes, including classes defined in external libraries, without modifying their source code. They provide a way to extend the functionality of classes without the need for inheritance or modifying their internal implementation. Extension functions enhance the expressiveness and readability of code by enabling the addition of new behavior to existing types.

Here are some key points about extension functions :

1. Syntax : Extension functions are defined outside of the class they extend, using the following syntax:
   fun ClassName.functionName(parameters): ReturnType {
       // Function implementation
   }​

2. Usage : Once an extension function is defined, it can be invoked directly on objects of the extended class, as if it were a member function of that class.
   val result = myObject.functionName()​

3. Scope : Extension functions are available within the scope where they are imported or defined. By default, they are not visible outside their containing file or package. However, you can import them explicitly to make them accessible in other files or packages.

4. Access to Properties : Inside an extension function, you can access the public properties and methods of the class being extended, just like in regular member functions.

5. Function Overloading : You can define multiple extension functions with the same name but different parameter signatures. The appropriate function is resolved based on the parameter types at the call site.
6. Nullability : Extension functions can be defined for nullable types, allowing them to be called on nullable objects. The null-safety rules apply to extension functions as well.

Here's a simple example to illustrate the usage of extension functions :
fun String.removeWhitespace(): String {
    return this.replace(" ", "")
}

fun Int.isEven(): Boolean {
    return this % 2 == 0
}

fun main() {
    val text = "Hello, World!"
    val modifiedText = text.removeWhitespace()
    println(modifiedText) // Output: Hello,World!

    val number = 7
    val isNumberEven = number.isEven()
    println(isNumberEven) // Output: false
}​
In the above example, two extension functions are defined. The `removeWhitespace()` extension function extends the `String` class and removes whitespace characters from a string. The `isEven()` extension function extends the `Int` class and checks whether a number is even. These extension functions can be invoked directly on objects of their respective types, as shown in the `main()` function.

Extension functions are a powerful feature in Kotlin that promote code reusability, readability, and maintainability. They allow you to add functionality to existing classes without modifying their source code, making it easier to work with classes from external libraries or enhance the capabilities of standard classes.
Advertisement