Extension Function in Kotlin

Kayvan Kaseb
Software Development
4 min readMar 17, 2020

--

Extension Function in Kotlin

Kotlin language supports the ability to extend a class with new functionality without implementing the inheritance concept by a class or using design pattern, like Decorator. This is accomplished via special indication, which is called Extension Function. Thus, this capability could be effective for becoming code more cleaner and easy to read, and it could reduce the code as well. This essay aims to consider Extension Function in Kotlin as an ability for following some best practices in Android development.

What is the definition of Extension Function?

Fundamentally, an extension function is a member function of a class, which is defined outside the class. For instance, if you need to use a method to the String class that returns a new string with first and last character eliminated, you can be able to write an extension method for it. In fact, this method is not already available in String class.

Advantages of using Extension Function

In general, extension functions have the potential to make your code more brief, readable, and logical by improving and removing boilerplate code from your project. Besides, less code means fewer opportunities for making errors. In addition to previous reasons, there are some other benefits could be mentioned as follows:

  1. It can be able to add functionality to a final class. It means the class do not need to be defined as a non-final class.
  2. It can be able to add functionality without sub-classing, which means the object reference and the its implementation can be mentioned in your base class.
  3. It follows some best-practices in Object-Oriented programming, particularly Open–closed principle (in SOLID principles), which indicates entities (classes, modules, functions, etc.) should be opened for extension, but closed for modification.

Kotlin Extension Function

Basically, 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 using a prefix receiver type (class name) and also with using method name (extension function) as follows:

fun <class_name>.<method_name>()

Generally, we call all methods from outside the class which are already defined inside the class. For instance, suppose that we want to call a method perimeter() of Circle class which is not defined in class. This indication Circle.perimeter() function is known as extension function, and Circle class is known as receiver type as well.

class Circle(val radius: Double){ 

fun area(): Double{
return Math.PI * radius * radius;
}
}
fun Circle.perimeter(): Double{ return 2 * Math.PI * radius;
}
fun main(){

val circle = Circle(5.5);
val perimeterValue = circle.perimeter()
println("Perimeter: $perimeterValue")
val areaValue = circle.area()
println("Area: $areaValue")
}

Extended Library Classes

In Kotlin, you can extend the library classes, as well as user-defined classes. As a matter of fact, the extension function could be added to library classes, and used in the same way as for user-defined classes. For example:

fun main(args: Array<String>){ 

fun Int.abs() : Int{

return if(this < 0)
}

println((-4).abs())
println(4.abs())
}

Nullable Receiver

Extension functions can be defined with the class type, which is nullable. In this situation, the check for null is added inside the extension function, and the appropriate value is returned. For instance, we are swapping the elements of Mutable List by using swap() method, but MutableList class does not support the swap() internally. Therefore, for addressing this issue, we should write an extension function for MutableList via swap() function.

funMutableList<Int>?.swap(first: Int, second: Int): Any{ 

if (this == null) return "null" //Checked the null-ability here!

else{
val temp = this[first]
this[first] = this[second]
this[second] = temp
return this
}
}
fun main(){ val list = mutableListOf(6,9,7)
println("Print the list :$list")
val result = list.swap(0, 2)
println("swapping the list :$result") //Output: [7, 10, 6]
}

Companion Object Extensions

As a matter of fact, a companion object is an object that is mentioned inside a class and specified with the companion keyword. Companion object is used to call the member function of class directly by using the class name in similar way to static keyword in Java. If a class includes companion object, we can define extension functions and properties for the companion object.

class SampleClass {
companion object { }
}
fun SampleClass.Companion.printTest() { println("Test") }fun main() {
SampleClass.printTest()
}

Furthermore, the companion object extension is being called by using the class name (qualifier). For example:

class SampleClass{      companion object{        fun create(sample :String): String{ 

return sample

}
}
}
fun SampleClass.Companion.printString(){ println("Companion Object Extensions")

}
fun main(args: Array<String>){ val sampleObject = SampleClass.printString("Print the string")
println(sampleObject)
}

In conclusion, Kotlin supports the ability to extend a class with new functionality without implementing the inheritance or using a design pattern design pattern. This is accomplished via special indication that is called Extension Function. This ability could be helpful for becoming code more cleaner and easy to read, and it could diminish the code as well. However, this method has some negative consequences. For instance, you cannot access the protected properties or functions of your base class.

--

--

Kayvan Kaseb
Software Development

Senior Android Developer, Technical Writer, Researcher, Artist, Founder of PURE SOFTWARE YAZILIM LİMİTED ŞİRKETİ https://www.linkedin.com/in/kayvan-kaseb