Skip to content

Kotlin Companion Object

Devrath edited this page Aug 24, 2022 · 1 revision
  • Companion object is similar to object and the member variables and the member functions of it can be accessed in the class where it is contained.
  • Companion object doesn't have a name, If a name is given to it then the caller class has to access it via its name.
  • Any caller can access the member variables and their functions of it without creating the instance of the outer class.
  • This pattern is useful when we want to expose some static behavior to the outside world where the creation of an instance is not needed.
Class SomeClass {
   Companion Object {
      private var count : Int = 0
      fun appendCount(){
          count++
      }
   }
}
Clone this wiki locally