Kotlin extension function
Last Updated :
03 Jan, 2022
Kotlin gives the programmer the ability to add more functionality to the existing classes, without inheriting them. This is achieved through a feature known as extensions. When a function is added to an existing class it is known as Extension Function. To add an extension function to a class, define a new function appended to the classname as shown in the following example:
Kotlin
package kotlin1.com.programmingKotlin.chapter1
class Circle (val radius: Double){
fun area(): Double{
return Math.PI * radius * radius;
}
}
fun main(){
fun Circle.perimeter(): Double{
return 2 *Math.PI*radius;
}
val newCircle = Circle( 2.5 );
println("Area of the circle is ${newCircle.area()}")
println("Perimeter of the circle is ${newCircle.perimeter()}")
}
|
Output:
Area of the circle is 19.634954084936208
Perimeter of the circle is 15.707963267948966
Explanation:
Here, a new function is appended to the class using dot notation with class Circle.perimeter(), and its return type is Double. In the main function, an object is created to instantiate the class Circle and invoked the function in println() statement. When the member function is invoked it returns the area of a circle and similarly, the extension function returns the perimeter of the circle.
Extended library class using extension function
Kotlin not only allows the user-defined classes to be extended but also the library classes can be extended. The extension function can be added to library classes and used in a similar way as for user-defined classes. The following example demonstrates an extension function created for a library class-
Kotlin
fun main(){
fun Int.abs() : Int{
return if ( this < 0 ) - this else this
}
println((- 4 ).abs())
println( 4 .abs())
}
|
Output:
4
4
Explanation: Here, we have extended the library function using an extension function. We performed the modulus operation on an integer value. We have passed the integer value -4 and 4 and obtained a positive value for both. If the parameter value is less than 0 then returns -(value) and if the parameter value is greater than zero returns the same value.
Extensions are resolved statically
One important point to note about the extension functions is that they are resolved statically i.e which extension function is executed depends totally on the type of the expression on which it is invoked, rather than on the type resolved on the final execution of the expression at runtime. The following example will make the above argument clear:
Kotlin
open class A(val a:Int, val b:Int){
}
class B():A( 5 , 5 ){}
fun main(){
fun A.operate():Int{
return a+b
}
fun B.operate():Int{
return a*b;
}
fun display(a: A){
print(a.operate())
}
display(B())
}
|
Output:
10
Explanation:
If you are familiar with Java or any other object-oriented programming language, you might notice in the above program, that since class B inherits class A and the argument passed display function is an instance of class B. The output should be 25 according to the concept of the dynamic method dispatch, but since the extension functions are statically resolved, so the operation function is called on type A. Hence the output is 10.
Nullable Receiver
Extension functions can also be defined with the class type that is nullable. In this case, when the check for null is added inside the extension function and the appropriate value is returned.
Example of an extension function as a nullable receiver –
Kotlin
class AB(val name: String){
override fun toString(): String {
return "Name is $name"
}
}
fun main(){
fun AB?.output(){
if ( this == null ){
println("Null")
} else {
println( this .toString())
}
}
val x = AB("Charchit")
x.output()
null .output()
}
|
Output:
Name is Charchit
Null
Companion Object Extensions
If a class contains a companion object, then we can also define extension functions and properties for the companion object. Companion object declaration –
Kotlin
class MyClass {
companion object {
fun display(){
println("Function declared in companion object")
}
}
}
fun main(args: Array<String>) {
val ob = MyClass.display()
}
|
Output:
Function declared in companion object
Just like the calling of the regular member function of the companion object, the extension function can be called using only the class name as the qualifier. Companion object extension example –
Kotlin
class MyClass {
companion object {
fun display(str :String) : String{
return str
}
}
}
fun MyClass.Companion.abc(){
println("Extension function of companion object")
}
fun main(args: Array<String>) {
val ob = MyClass.display("Function declared in companion object")
println(ob)
val ob2 = MyClass.abc()
}
|
Output:
Function declared in companion object
Extension function of companion object
Share your thoughts in the comments
Please Login to comment...