Google News
logo
Kotlin - Interview Questions
What is a companion object in Kotlin?
In Kotlin, a companion object is a special object that is tied to a specific class. It allows you to define properties and functions that can be accessed directly on the class itself, without the need for an instance of that class. The companion object is similar to static members in other programming languages, but with additional flexibility and capabilities.

Here are some key points about companion objects :

1. Declaration : The companion object is declared within the body of a class using the `companion` keyword.
   class MyClass {
       // ...

       companion object {
           // Properties and functions
           // ...
       }
   }​

2. Accessing Members : Members of the companion object can be accessed directly on the class name, similar to accessing static members in other languages.
   MyClass.myFunction()
   MyClass.myProperty​

3. Naming : By default, the name of the companion object is "Companion". However, you can provide a custom name by explicitly declaring the companion object.
   class MyClass {
       // ...

       companion object MyCompanion {
           // Properties and functions
           // ...
       }
   }​

4. Behavior : The companion object can access private members of the class, including private constructors, and can be used to encapsulate utility functions, constants, factory methods, or other shared functionality that relates to the class.

5. Implementing Interfaces : The companion object can also implement interfaces, allowing it to provide a common interface for accessing shared functionality.
6. Extension Functions : You can define extension functions on the companion object, which can be called directly on the class name, similar to static utility functions.

Here's an example to illustrate the usage of companion objects :
class MyClass {
    companion object {
        const val CONSTANT_VALUE = 42

        fun myFunction() {
            println("Hello from myFunction()")
        }
    }
}

fun main() {
    println(MyClass.CONSTANT_VALUE)
    MyClass.myFunction()
}​

In the above example, the companion object of the `MyClass` class contains a constant value (`CONSTANT_VALUE`) and a function (`myFunction()`). These members can be accessed directly on the class name without creating an instance of `MyClass`. The output of the program will be:
42
Hello from myFunction()​
Companion objects provide a way to define class-level members and share functionality across instances of a class. They are useful for encapsulating common functionality and constants, without the need for an explicit instance.
Advertisement