Signup/Sign In

Kotlin Companion Object

In this tutorial, we will learn about the Kotlin companion objects. In a class, properties are linked to the objects i.e. we can access them using object name. Each object will have all the properties with values of its own.

There might be a situation where we want to have some properties common for all objects of the class. These types of properties and methods are known as class level fields. They are initialized at the time of the creation of class by the compiler and shared between all the objects of the class. In other languages like Java, they are created using the static keyword. In Kotlin, a companion object is used to declare the class level fields.

Creating and accessing Companion Object

The companion object is created using the companion keyword. Let us create a class Employee and create a companion object with name Test:

class Employee {
    var salary:Int = 0
    fun printSalary(){
        println("Salary is: ${this.salary}")
    }
    companion object Test{
        var i: Int = 1
        fun printI(){
            println("Value of i: $i")
            i++
        }
    }
}

The Employee class contains a companion object named Test which contains a variable i and function printI(). The class also contains a variable salary and a function printSalary() which can be accessed using the object of the class.

Fields inside companion objects are accessed using the class name. They can also be accessed using both the class name or the object name. Let us use this class in the main() function:

fun main() {
    Employee.printI()       // Access printI() method using class name
    Employee.Test.printI()  // Access printI() method using class name and companion object name
}


Value of i: 1
Value of i: 2

Few important points regarding companion objects:

  • Companion objects are accessed using the class name instead of object names.

  • If the companion object name is missing, the default name Companion is assigned to it.

  • There can only be one companion object in a class.

  • A companion object is initialized when the class is loaded.

  • If we try to access class level fields using objects or objects fields using the class name, an error will be thrown:
    val employeeObject = Employee()
    employeeObject.printI()        // Error
    Employee.printSalary()         // Error

Summary

In this tutorial, we discussed companion objects in Kotlin. They can be considered as replacement of Java static keyword. They come handy when creating a class. In the next tutorial, we will discuss getters and setters in Kotlin.



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