Kotlin Extension Function

Kotlin Extension Function

Kotlin Extension Function

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 prefix receiver type with method name.

fun .

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){  
                    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
                    
                                    
                                

Kotlin 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.swap(index1: Int, index2: Int):MutableList) using list.swap(0,2) function call. The swap(0,2) function pass the index value of list inside MutableList.swap(index1: Int, index2: Int):MutableList) sxtension function.

                                        
                fun MutableList.swap(index1: Int, index2: Int):MutableList {  
                    al tmp = this[index1] // 'this' represents to the list  
                        this[index1] = this[index2]  
                        this[index2] = tmp  
                        return this  
                    }  
                    fun main(args: Array) {  
                    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?.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) {  
                        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]  
                        
                                        
                                    
I Hope you enjoy this blog

Thank You

Want a Team that Delivers Result ? Connect now with us.

-

Our Offices

INDIA

F-429, Phase 8B, Industrial Area, SAS Nagar, Punjab 160059

+91 82198-18163

USA

13506 Summerport Village Pky Suite 355 Windermere, FL 34786

+1 (321) 900-0079

CANADA

15 Meltwater Cres, Brampton L6P3V8

+1 (647) 892-6147