Kotlin Extension Function

The Kotlin extension function is a new feature of Kotlin. Without creating an object of class. It is known as an extension function. To add an extension function to a class define a new function appended to the class name as shown in the following example.

Example:

// A sample class to demonstrate extension functions

class Circle (val radius: Double){

// member function of class

fun area(): Double{

return Math.PI * radius * radius;

}

}

fun main(){

// Extension function created for a class Circle

fun Circle.perimeter(): Double{

return 2*Math.PI*radius;

}

// create object for class Circle

val newCircle = Circle(2.5);

// invoke member function

println("Area of the circle is ${newCircle.area()}")

// invoke extension function

println("Perimeter of the circle is ${newCircle.perimeter()}")

}

Output

The area of the circle is 34954084936208

The perimeter of the circle is 15.707963267948966

Extended library class using an extension function

Kotlin not only allows the user-defined classes to extend but also the library classes. The following example of library functions.

Example:

fun main(){

// Extension function defined for Int type

fun Int.abs() : Int{

return if(this < 0) -this else this

}

 

//abs method called 

println((-508).abs())

//abs method called 

println(508.abs())

}

Output

508

508

Happy coding!



365Bloggy May 8, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive