Kotlin companion object explanation with example

Introduction :

For normal classes, if we want to access any of its property, like calling a method or accessing any variable in the class, we need to create one object for that class. If we don’t want to create one class instance and access its members, we need to create one companion object. Unlike other programming languages like Java or Python, Kotlin doesn’t have the concept of static function.

How to declare a companion object :

Companion objects are declared using companion keyword. Just use that keyword in front of the object declaration and it will be a companion object. For example :

class Car{
    companion object Details{
        fun printDetails() = println("Car details")
    }
}

fun main() {
    Car.printDetails()
}

Here, we are declaring one companion object Details in the class Car. This object contains one function printDetails. We can call this function directly without creating an instance of the class like Car.printDetails().

We can also remove the name of the object :

class Car{
    companion object {
        fun printDetails() = println("Car details")
    }
}

fun main() {
    Car.printDetails()
}

companion objects are initialized when the class is loaded. We can have only one companion object per class. These objects can be accessed only via class names, not their instances.

Similar tutorials :