Open In App

Kotlin extension function

Last Updated : 08 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Kotlin provides a powerful feature called Extension Functions that allows us to add new functions to existing classes without modifying them or using inheritance. This makes our code more readable, reusable, and clean.

What is an Extension Function?

An extension function is a function that is defined outside a class, but can be called as if it were part of that class. We can use this feature on both user-defined classes and library classes (like String, Int, etc.).

Declare an Extension Function

To declare an extension function, we must do it in the following way.

fun ClassName.functionName(): ReturnType {
// function body
}

We use the class name followed by a dot (.), and then the name of the function.

Example:

Kotlin
class Circle(val radius: Double) {
    fun area(): Double {
        return Math.PI * radius * radius
    }
}

// Extension function
fun Circle.perimeter(): Double {
    return 2 * Math.PI * radius
}

fun main() {
    val circle = Circle(2.5)
    println("Area of the circle is ${circle.area()}")
    println("Perimeter of the circle is ${circle.perimeter()}")
}

Output: 

Area of the circle is 19.634954084936208  
Perimeter of the circle is 15.707963267948966

Explanation: 

Here, a new function is appended to the class using dot notation with class Circle.perimeter(), and its return type is Double. In the main function, an object is created to instantiate the class Circle and invoked the function in println() statement. When the member function is invoked it returns the area of a circle and similarly, the extension function returns the perimeter of the circle. 


Extension Functions on Library Classes

Kotlin not only allows the user-defined classes to be extended but also the library classes can be extended. The extension function can be added to library classes and used in a similar way as for user-defined classes. The following example demonstrates an extension function created for a library class- 

Kotlin
// Extension function defined for Int type
fun Int.abs(): Int {
    return if (this < 0) -this else this
}

fun main() {
    println((-4).abs())
    println((4).abs())
}

Output: 

4
4

Explanation:

We added a new function abs() to the Int type. It returns the absolute value of an integer. So whether the number is -4 or 4, the output is the positive version: 4.


Extensions are resolved statically

One important point to note about the extension functions is that they are resolved statically i.e which extension function is executed depends totally on the type of the expression on which it is invoked, rather than on the type resolved on the final execution of the expression at runtime. The following example will make the above argument clear:  

Kotlin
// Open class created to be inherited
open class A

// Class B inherits A
class B : A()

fun A.printInfo() = println("Called on A")
fun B.printInfo() = println("Called on B")

fun main() {
    val obj: A = B()
    obj.printInfo()
}

Output: 

Called on A

Explanation: 

If you are familiar with Java or any other object-oriented programming language, you might notice in the above program, that since class B inherits class A and the argument passed display function is an instance of class B. The output should be 25 according to the concept of the dynamic method dispatch, but since the extension functions are statically resolved, so the operation function is called on type A. Hence the output is 10. 


Nullable Receiver in Extension Functions

Extension functions can also be defined with the class type that is nullable. In this case, when the check for null is added inside the extension function and the appropriate value is returned.

Example:

Kotlin
// An extension function as a nullable receiver
fun String?.printName() {
    if (this == null) {
        println("Null")
    } else {
        println("Name is $this")
    }
}

fun main() {
    val name: String? = "Charchit"
    val nullName: String? = null

    name.printName()
    nullName.printName()
}

Output: 

Name is Charchit
Null

Explanation:

The receiver String? means the extension function can be called on a nullable string. Inside the function, we check if this is null and act accordingly.


Extension Functions for Companion Objects

If a class contains a companion object, then we can also define extension functions and properties for the companion object. 

Example: 

Kotlin
class MyClass {
    companion object
}

fun MyClass.Companion.showMessage() {
    println("Function declared in companion object")
}

fun main() {
    MyClass.showMessage()
}

Output: 

Function declared in companion object

We added a function showMessage() to the companion object of MyClass. We can call it using the class name, just like we do with static methods in Java.


Next Article
Article Tags :

Similar Reads