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 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. 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 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.Example of extension function declaration and its use
class Student{
fun isPassed(mark: Int): Boolean{
return mark>40
}
}
fun Student.isExcellent(mark: Int): Boolean{
return mark > 90
}
fun main(args: Array
Kotlin extension function example
fun MutableList
Extension Function as Nullable Receiver
funMutableList