Profile
March 2, 2023

Explanation of Kotlin's Companion Object Keyword

Learn about Kotlin's Companion Object keyword and how it allows you to create a singleton object within a class, which is shared among all instances of that class. Find examples and use cases.

Kotlin's companion object is a language feature that allows you to create a singleton object within a class. This object is shared among all instances of that class and can be accessed using the class name as a qualifier.

The companion object keyword is used to define this singleton object within a class. Here is an example:

class MyClass {
    companion object {
        fun myFunction() {
            println("This is a function in the companion object")
        }
    }
}

In this example, MyClass has a companion object defined inside it. This object contains a single function called myFunction(). To call this function, you don't need to create an instance of MyClass. Instead, you can access it using the class name as follows:

MyClass.myFunction()

This is useful when you want to group related functions together and make them easily accessible without needing an instance of the class. The companion object can also access private members of the class, which makes it useful for implementing factory methods or other design patterns.

In addition to functions, you can also define properties in the companion object:

class MyClass {
    companion object {
        val myProperty = "This is a property in the companion object"
    }
}

To access this property, you can again use the class name as a qualifier:

println(MyClass.myProperty)

The companion object can also implement interfaces and extend classes, just like any other object in Kotlin.

Last edited on August 6, 2023 by Admin

Latest articles