Kotlin companion objects allow you to define static members in a class. In this post, we'll take a look at what companion objects are and how to use them.
Companion objects are objects that are associated with a class. They are used to store static members in a class.
Static members are members that are associated with a class, not with an instance of a class. This means that you can access them without creating an instance of the class.
Companion objects are declared using the companion object
keyword. They can be used to store constants, utility functions, and factory methods.
Companion objects are declared using the companion object
keyword. They can be used to store constants, utility functions, and factory methods.
To access members of a companion object, you use the class name as a qualifier. For example, if you have a companion object named MyClass
in a file named MyClass.kt
, you would access its members like this:
MyClass.Companion.myFunction()
If you want to access members of a companion object from within the class, you can omit the companion
keyword. For example:
class MyClass {
companion object {
fun myFunction() {
// ...
}
}
}
In this post, we've looked at what companion objects are and how to use them. Companion objects are a great way to store static members in a class.