companion object kotlin

class MyClass {
    companion object {
        const val MY_CONSTANT = 42

        fun myFunction() {
            // Function implementation
        }
    }
}
  1. class MyClass: Declares a class named MyClass.

  2. companion object: Defines a companion object inside the class. A companion object is a singleton that is tied to the class rather than to instances of the class.

  3. const val MY_CONSTANT = 42: Declares a constant property named MY_CONSTANT with a value of 42 inside the companion object. Constants in Kotlin are declared using the const keyword.

  4. fun myFunction() { }: Declares a function named myFunction inside the companion object. This function may contain the implementation specific to the class.

Note: The use of companion object allows you to access the properties and functions defined inside it using the class name, similar to static members in other programming languages. For example, MyClass.MY_CONSTANT and MyClass.myFunction() would be valid usages.