WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Basic · question 20 of 100

What are the main differences between using companion objects and object declarations in Kotlin?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, both companion objects and object declarations are used to create objects. However, they differ in their behavior and intended use cases.

A companion object is created inside a class and can access private members of the class. It can be used to define constants, invoke factory methods, and implement static-like behavior. Here’s an example:

class MyClass {
    companion object {
        const val MY_CONSTANT = "Hello"
        
        fun myFactoryMethod(): MyClass {
            return MyClass()
        }
    }
}

Here, ‘MyClass‘ has a companion object that contains a constant and a factory method. These can be accessed using the companion identifier, like this:

val constantValue = MyClass.MY_CONSTANT
val instance = MyClass.myFactoryMethod()

On the other hand, object declarations are used to create a single instance of a class, without the ability to create multiple instances. They can be used to implement the Singleton design pattern, or simply to create a standalone object with a certain behavior. Here’s an example:

object MySingleton {
    fun doSomething() {
        // ...
    }
}

Here, ‘MySingleton‘ is an object declaration that contains a single function. This can be accessed directly, like this:

MySingleton.doSomething()

To summarize, companion objects are used to define static-like behavior and constants within a class, while object declarations are used to create single instances of a class, often for implementing Singleton behavior.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics