Sobes.tech
Middle

What is a 'companion object' in Kotlin and when should it be used?

sobes.tech AI

Answer from AI

A companion object in Kotlin is a special singleton object associated with a class, similar to static members in Java. It has access to the class's private members and can be called directly via the class name without creating an instance.

Used for:

  1. Factory methods: Creating class instances with more complex logic than a standard constructor.
    class User private constructor(val name: String) { // Private constructor
    
        // Factory method
        companion object {
            fun create(name: String): User {
                // Additional creation logic
                return User("User: $name")
            }
        }
    }
    
  2. Class-level constants: Storing common constants related to the class.
    class MyClass {
        companion object {
            const val DEFAULT_VALUE = 10
        }
    }
    
  3. Utility functions related to the class: Functions that are logically connected to the class but do not require an instance.
    class StringUtils {
        companion object {
            fun isEmptyOrNull(str: String?): Boolean {
                return str.isNullOrEmpty()
            }
        }
    }
    
  4. Implementing interfaces: companion object can implement interfaces, which is useful for providing some functionality without creating a class instance.
    interface Logger {
        fun log(message: String)
    }
    
    class DatabaseLogger {
        companion object : Logger {
            override fun log(message: String) {
                println("Database log: $message")
            }
        }
    }
    
What is a 'companion object' in Kotlin and when… - sobes.tech