Companion Objects

Not sure if you are ok with previous response, but there’s one more without the word static which generally confuse beginners :

in a class, almost everything is referenced by an instance of that class. This means that if you want to call a method of a class, you need to call the method from an instance of the class.

class X {
  fun hello() = println("hello")
}

fun main(){
  X() //creating the instance
    .hello() // and calling the method from it
}

so I said ‘almost everything’ because class are (by default) defined in the class (and not in the instance):

class X{
  class ClassInX{
    fun hello() = println("hello")
  }
}

fun main(){
  X.ClassInX() //note we don't use an instance of X(X() is just X) to use ClassInX, just the class
    .hello()
}

so now… there is a special “type” of class which are called object : in kotlin, an object is a class, and also an instance of it: the only instance of a class is itself. this means you don’t need to instanciate the class, it is already instaciate (only once, when the class is loaded, so this instance is shared by all the application):

class X{
  object ObjectInX{
    fun hello() = println("hello")
  }
}

fun main(){
  X.ObjectInX //like a class Z is bound to x
    //// BUT it is already an instance : we can call the method directly without () in previous line
    .helloz()  
}

so now there is a “special object”: the companion object : the companion object is an object which is called Companion. But the biggest thing of a companion object is that the compiler will add for you the .Companion when this can be done:

class X{
  companion object {
    fun hello() = println("hello")
  }
}

fun main(){
  X.Companion.hello() // works exactly the same that ObjectInX
  //and now the magic : 
  X.hello() //the compiler will deduce you want to use X.Companion.hello()
}

so if you understand all this, I now invite you to try to understand the notion of “static” which is quite important I think (and present in a lot of languages).

1 Like