Kotlin allows us to “extend” classes without inheriting them by using extension functions. A function is said to be an extension function if it is added to the existing class.
We can define an extension function outside the class using the class name. We can then call it like other methods of the class.
Let’s look at the syntax of the extension function given below:
fun classname.functionName()
A class can either be a primitive or a user-defined type.
Let’s have a look at an example in which we implement the extension function for a user-defined type.
class Circle (val radius: Double){fun area(): Double{return Math.PI * radius * radius;}}fun Circle.diameter(): Double{return 2*radius;}fun main(){val circle1 = Circle(5.0);println("Area of the circle is ${circle1.area()}")println("diameter of the circle is ${circle1.diameter()}")}
Circle
class with a property radius
of the Double
datatype. We also define a method area()
, which will return the area of the circle.diameter()
, which will return the diameter of the circle.Circle
class.area()
of the Circle
class.diameter()
of the Circle
class.Let’s have a look at another example. In this example, we implement the extension function for a primitive type Int
.
fun Int.square(): Int{return this*this}fun main(){val square: Int = 3.square()println("Squre of 3 is $square")}
square()
, which will return the square of the given Int
value.square()
for the Int
type.Free Resources