Companion Object in Kotlin

· 1 min read
Companion Object in Kotlin

Kotlin provides a brand new keyword companion which not exists in other programming languages. But don't be panic, it is not something new when you have one step closer. A companion object is considered as a very special object that is associated with a class, which many of us will think it is quite similar to a static object in other programming languages.

Definition of Companion Object

A companion object is defined within a Kotlin class with the companion keyword. Let's take a look at one example to get some impression first.

class CompanionClass {
  companion object CompanionObject {
    val num = 10
    fun getText() = "some text"
  }
}

println(CompanionClass.CompanionObject.num)         // 10
println(CompanionClass.CompanionObject.getText())   // some text

In the above example, We can access the property num and method getText() directly via class name without recreating an new instance of the class. Also companion object CompanionObject has the exact same visibility as its outer class, in other words it can be accessed from other places within the same package as the class,

A companion object can therefore contain both properties and methods. Just like a standard object, it can be used to store shared data or implement utility functions that can be accessed by all instances of the other classes. e.g. A typical use is to create singletons.

As we all know, there is no static keyword in kotlin. So the other common use case is that companion object is used to created static variable or method.  

More conveniently, we can even ignore the companion object name like this:

class CompanionClass {

    companion object {
        val num = 10
        fun getText() = "some text"
    }
}

println(CompanionClass.num)                         // 10
println(CompanionClass.getText())                   // some text

Summary

Overall, companion objects in Kotlin provide a convenient way to define and access shared data and utility functions related with a class which is similar to the static property and methods in other programming languages.