Kotlin: Difference between object and companion object in a class

There are two different types of object uses, expression and declaration.

Object Expression

An object expression can be used when a class needs slight modification, but it’s not necessary to create an entirely new subclass for it. Anonymous inner classes are a good example of this.

button.setOnClickListener(object: View.OnClickListener() {
    override fun onClick(view: View) {
        // click event
    }
})

One thing to watch out for is that anonymous inner classes can access variables from the enclosing scope, and these variables do not have to be final. This means that a variable used inside an anonymous inner class that is not considered final can change value unexpectedly before it is accessed.

Object Declaration

An object declaration is similar to a variable declaration and therefore cannot be used on the right side of an assignment statement. Object declarations are very useful for implementing the Singleton pattern.

object MySingletonObject {
    fun getInstance(): MySingletonObject {
        // return single instance of object
    }
}

And the getInstance method can then be invoked like this.

MySingletonObject.getInstance()

Companion Object

A companion object is a specific type of object declaration that allows an object to act similar to static objects in other languages (such as Java). Adding companion to the object declaration allows for adding the “static” functionality to an object even though the actual static concept does not exist in Kotlin. Here’s an example of a class with instance methods and companion methods.

class MyClass {
  companion object MyCompanionObject {
    fun actsAsStatic() {
      // do stuff
    }
  }
  
  fun instanceMethod() {
    // do stuff
  }
}

Invoking the instance method would look like this.

var myClass = MyClass()
myClass.instanceMethod()

Invoking the companion object method would look like this.

MyClass.actsAsStatic()

See the Kotlin docs for more info.

Leave a Comment

404 Not Found

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.