Table of contents
1.
Introduction
2.
Kotlin Extensions
3.
Extending library class using an extension function
4.
How are Extensions Resolved?
5.
Companion Object Extensions
5.1.
Companion Object
5.2.
Extensions on Companion Object
6.
FAQs
7.
Key Takeaways  
Last Updated: Mar 27, 2024

Kotlin Extensions

Author Pradeep Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will discuss Extensions in Kotlin. We will see how an extension is defined and used in a Kotlin Program. To add more functionality to an existing Kotlin class, we can use Extensions.

We will also look at companion objects and see how extensions can be implemented to classes containing companion objects. In the next section, we will study Kotlin Extensions in detail.

Kotlin Extensions

In Kotlin, Extensions are used to extend the functionality of an existing class without actually inheriting them. You can add a new function to a class using extensions, and the new function added is called an Extension function. An extension function has the same syntax as a regular function, with the exception that the name of the class followed by a dot operator is inserted before the function name. For example,

// Creating the Calculator class
// It takes a and b as arguments and performs some basic operations
class Calculator(val a: Int, val b: Int){
    // add method
    fun add(){
        println("$a + $b = ${a+b}")
    }
    // subtract method
    fun subtract(){
        println("$a - $b = ${a-b}")
    }
    // division method
    fun division(){
        println("$a / $b = ${a/b}")
    }
}

fun main(){
    // Extensions function created for the Calculator Class
    // Multiply function
    fun Calculator.multiply(){
        println("$a * $b = ${a*b}")
    }
    // creating an object of Calculator Class
    val ob = Calculator(10,5);
    // Calling the add function to calculate the sum of 10 and 5
    ob.add()
    // Calling the subtract function to calculate the difference of 10 by 5
    ob.subtract()
    // Calling the multiply function to calculate the multiplication of 10 by 5
    ob.multiply()
    // Calling the division function to calculate the division of 10 by 5
    ob.division()
}

Output:

10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2

Extending library class using an extension function

Library class in Kotlin can also be extended just like the way we extend a user-defined class. You can also add extension functions to a library class the way we add it to a user-defined class. For example,

fun main(){
    // Extension function for Int type
    fun Int.category() {
        if(this<0){ // check if the given number is less than 0 or not
            println("This is a negative number")
        }
        else if(this == 0){ // check for zero
            println("Zero is neither positive nor negative")
        }
        else{ // check for positive numbers
            println("This is a positive number")
        }
    }
    var n = -10 // negative number
    var z = 0 // zero
    var p = 35 // positive function
    // Calling the category function to check the category of a number
    n.category()
    z.category()
    p.category()
}

Output:

This is a negative number
Zero is neither positive nor negative
This is a positive number

How are Extensions Resolved?

Extensions in Kotlin are resolved statically, i.e., the extension function to be invoked depends on the type of the expression it is called upon, and not on the type obtained after resolving the expression at runtime on final execution. The below example will clarify the above-mentioned argument:

// Creating an abstract class Animal
abstract class Animal(){
}
// Inheriting the abstract class Animal
class Cat: Animal(){
}

fun main(){
    // Extension function print() for the Animal Class
    fun Animal.print(){
        println("Print function of Animal Class is Invoked")
    }
    // Extension function print() for the Cat Class
    fun Cat.print(){
        println("Print function of Cat Class is Invoked")
    }
    // function to check which method is getting invoked
    fun check(a: Animal){
        a.print()
    }
    val c = Cat()
    check(c) // Calling the check function
}

Output:

Print function of Animal Class is Invoked

Companion Object Extensions

Before moving on to the extensions of the Companion object, let’s first discuss what companion objects are.

Companion Object

Companion Object can be used inside a Kotlin Class. The properties of a companion object are not associated with a particular instance of that class, instead they are associated with that class itself. For example,

// foo class
class foo{
    // declaring a companion object
    companion object{
        // square function which take one integer parameter
        fun square(a: Int){
            println("The Square of $a: ${a*a}")
        }
    }
}

fun main(){
    // Invoking the square function
    foo.square(5)
}

Output:

The Square of 5: 25

Extensions on Companion Object

Extension function can be defined for a class having a companion object. In the below example, we will see how we can define an extension function for the companion object of a class.

// foo class
class foo{
    // declaring a companion object
    companion object{
        // square function which take one integer parameter
        fun square(a: Int){
            println("The Square of $a: ${a*a}")
        }
    }
}

fun main(){
    // Adding cube function using extensions
    fun foo.Companion.cube(a: Int){
        println("The Cube of $a: ${a*a*a}")
    }
    // Invoking the square function
    foo.square(5)
    // Invoking the cube function
    foo.cube(5)
}

Output:

The Square of 5: 25
The Cube of 5: 125

FAQs

  1. What is the purpose of using Extensions in Kotlin?
    Extensions allow you to add more functionality to an existing Kotlin class without having to inherit from them.
     
  2. How do you invoke an extension function?
    You can call an extension function the same way you call a regular method of a class.
     
  3. What is the nature of extension functions?
    Extension functions in Kotlin are static in nature. 

Key Takeaways  

Cheers if you reached here!!!

In this blog, we learned about Kotlin Extensions. We discussed how an extension can be declared and used in a Kotlin program. Additionally, we looked at companion objects and how extensions can be implemented to classes containing companion objects.

After reading this blog, I believe you will be able to work with Kotlin Extensions smoothly. If you wish to learn about Kotlin Loops, you can check out our other article on Kotlin LoopsAnd to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website.


Check out this problem - First Missing Positive 

Live masterclass