Kotlin – Extension

Kotlin extension function provides a facility to “add” methods to class without inheriting a class or using any type of design pattern. The created extension functions are used as a regular function inside that class.The extension function is declared with a prefixreceivertype with method name.

fun <class_name>.<method_name>()

In the above declaration, <class_name> is a receiver type and the <method_name>() is an extension function.

  • Example of extension function declaration and its use :

In general, we call all methods from outside the class which are already defined inside the class.In below example, a Student class declares a method is Passed() which is called from main() function by creating the object student of Student class.Suppose that we want to call a method (say isExcellent()) of Student class which is not defined in class. In such situation, we create a function (isExcellent()) outside the Student class as Student.isExcellent() and call it from the main() function. The declare Student.isExcellent() function is known as extension function, where Student class is known as receiver type.

class Student{
    fun isPassed(mark: Int): Boolean{
        return mark>40
    }
}
    fun Student.isExcellent(mark: Int): Boolean{
        return mark > 90
    }
    fun main(args: Array<String>){
        val student = Student()
        val passingStatus = student.isPassed(55)
        println("student passing status is $passingStatus")

        val excellentStatus = student.isExcellent(95)
        println("student excellent status is $excellentStatus")
    }

Output :

student passing status is true
student excellent status is true

The above example only demonstrates about how to declare an extension function.

  • extension function example :

Let’s see the real example of extension function. In this example, we are swapping the elements of MutableList<> using swap() method. However, MutableList<>class does not provide the swap() method internally which swap the elements of it. For doing this we create an extension function for MutableList<> with swap() function.The list object call the extension function (MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int>) using list.swap(0,2) function call. The swap(0,2) function pass the index value of list inside MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int>) sxtension function.

fun MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int> {
val tmp = this[index1] // 'this' represents to the list
    this[index1] = this[index2]
    this[index2] = tmp
    return this
}
fun main(args: Array<String>) {
    val list = mutableListOf(5,10,15)
    println("before swapping the list :$list")
    val result = list.swap(0, 2)
    println("after swapping the list :$result")
}

Output :

before swapping the list :[5, 10, 15]
after swapping the list :[15, 10, 5]

Extension Function as Nullable Receiver

The extension function can be defined as nullable receiver type. This nullable extension function is called through object variable even the object value is null. The nullability of object is checked using this == null inside the body.Let’s rewrite the above program using extension function as nullable receiver.

funMutableList<Int>?.swap(index1: Int, index2: Int): Any {
    if (this == null) return "null"
    else {
        val tmp = this[index1] // 'this' represents to the list
        this[index1] = this[index2]
        this[index2] = tmp
        return this
    }
}
fun main(args: Array<String>) {
    val list = mutableListOf(5,10,15)
    println("before swapping the list :$list")
    val result = list.swap(0, 2)
    println("after swapping the list :$result")
}

Output :

before swapping the list :[5, 10, 15]
after swapping the list :[15, 10, 5]

Companion Object Extensions

A companion object is an object which is declared inside a class and marked with the companion keyword. Companion object is used to call the member function of class directly using the class name (like static in java).A class which contains companion object can also be defined as extension function and property for the companion object.

  • Example of companion object : In this example, we call a create() function declared inside companion object using class name (MyClass) as qualifier.
class MyClass {
    companion object {
        fun create():String{
            return "calls create method of companion object"
        }
    }
}
fun main(args: Array<String>){
val instance = MyClass.create()
}

Output :

calls create method of companion object
  • Companion object extensions example : Let’s see an example of companion object extensions. The companion object extension is also being called using the class name as the qualifier.
class MyClass {
    companion object {
        fun create(): String {
            return "calling create method of companion object"
        }
    }
}
fun MyClass.Companion.helloWorld() {
    println("executing extension of companion object")
}
fun main(args: Array<String>) {
    MyClass.helloWorld() //extension function declared upon the companion object
}

Output :

executing extension of companion object

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.