What is a Companion Object ?

In Kotlin, a companion object is a special type of object declaration that is tied to a specific class. It allows you to define members (properties and functions) that belong to the class itself rather than to instances of the class.

Key Characteristics :

  • Scoped to the Class: You don't need to create an object (instance) to access its contents.

  • Single Instance: Only one companion object exists for each class.

  • Access to Private Members: The companion object can access private members of its containing class.

  • Interface Implementation: Unlike Java's static, a companion object can implement interfaces and be treated like a real object.

class User(val id: Int, val name: String) {
    
    // This is the companion object
    companion object {
        const val MIN_PASSWORD_LENGTH = 8
        
        fun createDefaultUser(): User {
            return User(0, "Guest")
        }
    }
}

// Accessing members directly via the class name
fun main() {
    println(User.MIN_PASSWORD_LENGTH)      // Output: 8
    val guest = User.createDefaultUser()   // Creates a User instance
}

The Lifecycle of a Companion Object :

1. Compile Time

At compile time, the Kotlin compiler generates a nested class inside your main class. If you named your companion object "Factory", it creates a class named MyClass$Factory. If you didn't name it, it defaults to MyClass$Companion.

2. Runtime (The Creation Point)

The companion object is lazy-loaded. It doesn't exist when the program starts; it is created only when:

  • The class is first accessed (e.g., calling a method or property).

  • An instance of the class is created.

  • The companion object itself is referenced.

Characteristics :

  • The Companion Object is a "Singleton": Its init block is your chance to set up things like database drivers or global constants that all instances will share.
  • Top-to-Bottom: Inside the class, init blocks and property initializers are executed in the order they appear in the source code.
  • Static vs. Instance: In the background (JVM), the Companion init block is compiled into a static {} block, while the Class init blocks are moved into the constructors.

Comments

Popular posts from this blog

What is a Coroutine? Why is it better than threads?

What are Coroutine Builders?

Sealed Classes and Sealed Interfaces