Sobes.tech
Junior

Explain what a 'companion object' is in Kotlin and in which cases it should be used.

sobes.tech AI

Answer from AI

companion object — a special object associated with a class but not an instance of it. It acts like static members in Java.

Key points:

  • Declared inside a class using the companion object keyword.
  • Has access to the class's private members.
  • Can have a name, but usually it is omitted (default name is Companion).
  • Members of the companion object can be accessed directly via the class name without creating an instance.

Examples of usage:

  • Factory methods: For creating class instances with more complex initialization logic than regular constructors.

    class MyClass private constructor(val value: String) { // Private constructor
    
        companion object {
            fun create(input: String): MyClass { // Factory method
                // Input processing logic
                return MyClass("Processed: $input")
            }
        }
    }
    
    fun main() {
        val instance = MyClass.create("some data") // Using factory method
        println(instance.value)
    }
    
  • Class-level constants: To define values that should be accessible without creating an instance.

    class Constants {
        companion object {
            const val DEFAULT_VALUE = "default" // Constant
        }
    }
    
    fun main() {
        println(Constants.DEFAULT_VALUE) // Access to constant
    }
    
  • Interface implementation: companion object can implement interfaces, which is useful for mimicking static factories with shared functionality.

    interface Factory<T> {
        fun create(): T
    }
    
    class MyData(val id: Int) {
        companion object : Factory<MyData> {
            private var nextId = 0
            override fun create(): MyData {
                return MyData(nextId++)
            }
        }
    }
    
    fun main() {
        val data1 = MyData.create()
        val data2 = MyData.create()
        println(data1.id)
        println(data2.id)
    }
    
  • Extensions: companion object can be extended, allowing adding "static" methods to a class from outside.

    class MyUtil {
        companion object {
            // Empty companion object
        }
    }
    
    fun MyUtil.Companion.helperMethod() { // Extension of companion object
        println("Called helper method")
    }
    
    fun main() {
        MyUtil.helperMethod()
    }
    

Overall, companion object should be used when functionality logically related to the class is needed but does not require an instance of that class. It is a more idiomatic Kotlin way to achieve what static members do in Java, offering greater flexibility (e.g., in implementing interfaces and extensions). It should not be overused for storing state that should be unique to each instance.

Explain what a 'companion object' is in Kotlin and in… - sobes.tech