How to Use Companion Object in Kotlin: Syntax and Examples
companion object is a special object inside a class that allows you to define members that belong to the class itself, not to instances. You use companion object to create static-like functions or properties accessible via the class name.Syntax
A companion object is declared inside a class using the keyword companion object. It can have a name or be anonymous. Members inside it can be accessed using the class name without creating an instance.
- companion object: declares the companion object block.
- Members: functions or properties inside companion object act like static members.
- Access: Use
ClassName.memberto access them.
class MyClass { companion object { val constant = 42 fun greet() = "Hello from companion!" } } fun main() { println(MyClass.constant) println(MyClass.greet()) }
Example
This example shows a class Calculator with a companion object that has a function to add two numbers. You can call this function directly on the class without creating an object.
class Calculator { companion object { fun add(a: Int, b: Int): Int { return a + b } } } fun main() { val result = Calculator.add(5, 7) println("Sum is: $result") }
Common Pitfalls
One common mistake is trying to access companion object members through an instance instead of the class name, which is allowed but not recommended for clarity. Another is forgetting that companion objects are singleton objects, so they cannot hold instance-specific data.
Also, naming the companion object is optional but can help when you want to implement interfaces or have multiple companion objects (rare).
class Example { companion object Named { fun info() = "Info from named companion" } } fun main() { // Correct access println(Example.info()) // Access via companion object name println(Example.Named.info()) }
Quick Reference
| Feature | Description | Usage Example |
|---|---|---|
| Declaration | Use companion object inside a class | companion object { ... } |
| Access | Access members via class name | ClassName.member |
| Naming | Optional to name companion object | companion object MyName { ... } |
| Static-like | Members behave like static members in Java | fun greet() = "Hi" |
| Singleton | Only one companion object per class | class MyClass { companion object { } } |
Key Takeaways
companion object to create static-like members inside a Kotlin class.