Kotlin companion object explained with examples

When you define a class in Kotlin, you need to create an instance of that class before you can access the class methods and properties.

For example, suppose you have a Car class with the following detail:

class Car {
    var category = "Sedan"
    fun start() = println("The car is starting..")
}

To access the category and start() of the Car above, you need to create an instance of the class:

val car = Car()
car.start() // The car is starting..
car.category = "Minivan"

A Kotlin companion object is a way of writing methods and properties of a class that can be called without having to create an instance of that class.

The methods and properties that you put inside the companion object is also known as static members of the class.

Here’s how you create a companion object in Kotlin:

class Car {
    companion object {
        var category = "Sedan"
        fun start() = println("The car is starting..")
    }
}

A companion object can be named as shown below:

class Car {
    companion object MyObject{
        var category = "Sedan"
        fun start() = println("The car is starting..")
    }
}

But since each Kotlin class can only have one companion object, you don’t need to give it a name.

Now you can directly call the methods and properties that are defined inside the companion object as shown below:

class Car {
    companion object {
        var category = "Sedan"
        fun start() = println("The car is starting..")
    }
}

Car.category = "Minivan"
Car.start()

And that’s all there is to a companion object in Kotlin.

You can still write a normal method outside of the companion object in the same class as shown below:

class Car {
    companion object {
        var category = "Sedan"
        fun start() = println("The car is starting..")
    }

    fun activateGps() = println("Turn on GPS")
}

To access the activateGps() method, you need to create an instance of the Car class.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.