Signup/Sign In

Kotlin Extension Function

In this tutorial we will discuss about Extension Functions in Kotlin. Kotlin provides the facility to add new functionality to already existing classes. For this, there is no need to inherit them. It can be achieved through special declaration called extensions.

Kotlin Extension Functions

Kotlin Extensions provides functionality to add a new function to an existing class. This function is known as extension function. We can add extension functions to a User defined class as well as to a Library class.

Let us create a class InterestCalculator which contains a function simpleInterest() to calculate simple interest:

class InterestCalculator(var principal: Double, var rate: Double, var time: Double){
    fun simpleInterest(): Double{
        return this.principal * this.rate * this.time * 0.01
    }
}

Suppose, later we want to add functionality to calculate compound interest but the class structure cannot be changed. In this scenario we can use extension functions.

Extension functions are added using . operator after the class name. Here is the syntax to add an extension function to a class:

fun ClassName.functionName(): returnType {
    // body of function
}

Let us add an extension function compoundInterest() to InterestCalculator class and call it. Extension functions are called in similar manner as class functions are called.

Here's the code:

fun InterestCalculator.compoundInterest(): Double {
    val amount = this.principal * Math.pow(1 + (this.rate / 100), this.time)
    return amount - this.principal

}
fun main() {
    val educationLoanCalculator = InterestCalculator(100000.0, 11.0, 4.0)
    println("Simple interest for this education loan is ${educationLoanCalculator.simpleInterest()}")
    println("Compound interest for this education loan is ${educationLoanCalculator.compoundInterest()}")
}


Simple interest for this education loan is 44000.0
Compound interest for this education loan is 51807.041000000056

Similarly, we can add extension functions to any library class also.

Extension function to Companion Objects

We can also add an extension function to a companion object in a class. Let us edit the InterestCalculator class and add a companion object which contains a function printSimpleInterestFormula():

class InterestCalculator(var principal: Double, var rate: Double, var time: Double){
    fun simpleInterest(): Double{
        return this.principal * this.rate * this.time * 0.01
    }
    companion object {
        fun printSimpleInterestFormula(){
            println("Simple interest formula is: principal * rate * time * 0.01")
        }
    }
}

Now add a function printCompoundInterestFormula() to the companion object and call it from main() function:

fun InterestCalculator.Companion.printCompoundInterestFormula(){
    println("Compound interest formula is: principal * ( 1 + rate / 100) ^ time")
}
fun main() {
    InterestCalculator.printSimpleInterestFormula()
    InterestCalculator.printCompoundInterestFormula()
}


Simple interest formula is: principal * rate * time * 0.01
Compound interest formula is: principal * ( 1 + rate / 100) ^ time

Summary

In this tutorial we learned about extension functions in Kotlin which comes in handy if you want to add more functionality to any class present in some different library. The extension functions are mostly used in case of library classes. From the next tutorial we start learning about Exception handling in Kotlin.



About the author:
I'm a writer at studytonight.com.