companion object kotlin
class MyClass {
companion object {
const val MY_CONSTANT = 42
fun myFunction() {
// Function implementation
}
}
}
class MyClass
: Declares a class namedMyClass
.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.const val MY_CONSTANT = 42
: Declares a constant property namedMY_CONSTANT
with a value of 42 inside the companion object. Constants in Kotlin are declared using theconst
keyword.fun myFunction() { }
: Declares a function namedmyFunction
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.