Home » Kotlin companion object

Kotlin companion object

  • by
Kotlin companion object

1. Overview

In this article, we will learn about the Kotlin companion object. To learn more about other Kotlin topics, refer to these articles.

Unlike Java, the actual static concept does not exist in Kotlin (static fields or methods). However, the companion objects allow adding static functionality to a class and are singleton objects.

2. Kotlin singleton object declaration

As we all know, the singleton pattern restricts the instantiation of a class to one “single” instance. This is useful when you want to coordinate actions across the system using exactly one object.

Kotlin makes it easy to declare singletons.

The syntax of the Object declaration using the object keyword is:

object <name of singleton> {
    
}

Just like a variable declaration, an object declaration is not an expression, and we cannot use it on the right-hand side of an assignment statement.

3. Kotlin companion object

A companion object is a specific type of object declaration that allows an object to act similarly to static objects in other languages (such as Java).

You can mark an object declaration inside a class with the companion keyword:

class Utility {
    companion object Factory {
        fun create(): Utility = Utility()
    }
}

The companion object initialization happens when the class is loaded (typically the first time it’s referenced by other code that is being executed)

3.1. Access the members of the companion object

You can access the members of the companion object simply by using the class name as the qualifier:

val instance = Utility.create()

You can skip specifying the name of the companion object and use the name Companion to access it:

class Utility {
    companion object { }
}

val x = Utility.Companion

Class members can access the private members of the corresponding companion object.

3.2. Static members

Note that even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces:

interface Vehicle {
    fun create(): Vehicle
}

class MyClass {
    companion object : Vehicle {
        override fun create(): Vehicle = // your code
    }
}

However, Kotlin can generate real static methods for functions defined in companion objects on the JVM if you annotate those functions as @JvmStatic.

class C {
    companion object {
        @JvmStatic fun callStatic() {}
        fun callNonStatic() {}
    }
}

Now, callStatic() is static in Java while callNonStatic() is not:

C.callStatic(); // works fine
C.callNonStatic(); // error: not a static method
C.Companion.callStatic(); // instance method remains
C.Companion.callNonStatic(); // the only way it works

4. Conclusion

To sum up, we have learned the Kotlin companion object with few samples.

Leave a Reply

Your email address will not be published. Required fields are marked *