What is Companion Object in Kotlin: Simple Explanation and Example
companion object is a special object inside a class that allows you to define members that belong to the class itself, not to instances. It acts like a place for static methods and properties, letting you call them using the class name without creating an object.How It Works
Imagine a class as a blueprint for making houses. Normally, each house has its own features like color or number of rooms. But sometimes, you want to have something shared by all houses, like the builder's name or a common rule. In Kotlin, a companion object is like that shared space inside the blueprint.
It is an object declared inside a class with the keyword companion. This object can hold functions and properties that belong to the class itself, not to any single instance. You can think of it as a hidden singleton object that Kotlin creates for you, so you can call its members using the class name directly.
This helps when you want to group related static-like methods or constants inside the class without using Java-style static keywords.
Example
This example shows a class with a companion object that has a function and a property. You can call them using the class name without creating an instance.
class MyClass { companion object { val greeting = "Hello from companion" fun sayHello() { println(greeting) } } } fun main() { MyClass.sayHello() // Calls the companion object's function println(MyClass.greeting) // Accesses the companion object's property }
When to Use
Use a companion object when you want to create functions or properties that belong to the class itself, not to any object made from it. This is useful for factory methods, constants, or utility functions related to the class.
For example, if you want to create an object from a string or number without calling the constructor directly, you can put a factory method inside the companion object. Also, constants that belong to the class can be stored there for easy access.
Key Points
- A
companion objectis a singleton object inside a class. - It allows calling methods and accessing properties using the class name.
- It replaces Java's static members in a cleaner way.
- Useful for factory methods, constants, and utilities related to the class.