DEV Community

Ben
Ben

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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,

Top comments (0)