In Kotlin, both companion objects and object declarations are used to create objects. However, they differ in their behavior and intended use cases.
A companion object is created inside a class and can access private members of the class. It can be used to define constants, invoke factory methods, and implement static-like behavior. Here’s an example:
class MyClass {
companion object {
const val MY_CONSTANT = "Hello"
fun myFactoryMethod(): MyClass {
return MyClass()
}
}
}
Here, ‘MyClass‘ has a companion object that contains a constant and a factory method. These can be accessed using the companion identifier, like this:
val constantValue = MyClass.MY_CONSTANT
val instance = MyClass.myFactoryMethod()
On the other hand, object declarations are used to create a single instance of a class, without the ability to create multiple instances. They can be used to implement the Singleton design pattern, or simply to create a standalone object with a certain behavior. Here’s an example:
object MySingleton {
fun doSomething() {
// ...
}
}
Here, ‘MySingleton‘ is an object declaration that contains a single function. This can be accessed directly, like this:
MySingleton.doSomething()
To summarize, companion objects are used to define static-like behavior and constants within a class, while object declarations are used to create single instances of a class, often for implementing Singleton behavior.