What is a Companion Object?

When you are new to Kotlin and you are familiar with Java, you may be wondering how you can create static methods and fields in Kotlin. Unlike Java, Kotlin doesn’t have a static keyword. Kotlin has the concept of a companion object.

How to create a Companion Object?

You create it inside of a class with the syntax “companion object{}

Now all functions and fields inside the companion object are used like they are “static”.

How to call it from Kotlin

To call the functions/fields from a companion object you use the class and call the functions/fields.

How to call it from Java

By default you call companion functions/fields like “KotlinClassName”.Companion.”MethodName”

But Kotlin has the @JvmStatic Annotation.

Functions and fields that are annotated, can be used from Java like they are usual static functions

How does it work on the JVM

You can use Intellij/Android Studio to see the bytecode that the Kotlin Compiler generates.
You can find the menu entry under Tools->Kotlin->Show Kotlin Bytecode

When you click on Decompile you can see what the Java equivalent to your Kotlin class would look like.

As you can see a companion object is compiled to public static final class Companion inside the Printer class.

What else can you do with companion objects?

  1. Note: A Kotlin class can only have one companion object
  2. You can give a companion object a name

  3. Inheritance and Interfaces
    A companion object can extend classes and implement interfaces. But you can not extend companion object because they are final classes.

References

https://kotlinlang.org/docs/reference/object-declarations.html