Companion Object vs Static in Kotlin: Key Differences and Usage
companion object is used to define members tied to a class rather than instances, replacing Java's static keyword which Kotlin does not support. Companion objects allow creating singleton-like objects inside classes, while static is a keyword for class-level members in Java.Quick Comparison
This table summarizes the main differences between Kotlin's companion object and Java's static keyword.
| Aspect | Companion Object (Kotlin) | Static Keyword (Java) |
|---|---|---|
| Definition | Singleton object inside a class | Class-level member keyword |
| Language Support | Kotlin only | Java and other JVM languages |
| Syntax | object inside class with companion modifier | Keyword static before member |
| Inheritance | Can implement interfaces | Cannot implement interfaces |
| Initialization | Initialized lazily on first access | Initialized when class loads |
| Access | Via class name or import | Via class name directly |
Key Differences
companion object in Kotlin is a special singleton object declared inside a class. It allows you to define functions and properties that belong to the class itself, not to any instance. Unlike Java's static keyword, Kotlin does not have static members; instead, companion objects serve this purpose.
One important difference is that companion objects are real objects and can implement interfaces or have their own state. They are initialized lazily when first accessed, which can improve startup performance. In contrast, Java's static members are initialized when the class is loaded by the JVM.
Accessing members inside a companion object requires referencing the companion object or importing its members, while Java's static members are accessed directly via the class name. This design makes Kotlin more consistent with its object-oriented principles.
Code Comparison
Here is how you define and use a static-like member in Java using the static keyword.
public class Example { public static int count = 0; public static void printCount() { System.out.println("Count is: " + count); } public static void main(String[] args) { Example.count = 5; Example.printCount(); } }
Companion Object Equivalent
This Kotlin code shows how to achieve the same behavior using a companion object.
class Example { companion object { var count = 0 fun printCount() { println("Count is: $count") } } } fun main() { Example.count = 5 Example.printCount() }
When to Use Which
Choose companion object in Kotlin when you want to define class-level members with the flexibility of an object, such as implementing interfaces or holding state. It fits Kotlin's design and supports lazy initialization.
Use static in Java when you need simple class-level members without the overhead of an object. Since Kotlin does not support static, companion objects are the idiomatic way to achieve similar functionality.