Companion Object (Kotlin)
A companion object is a single object declared inside a class with the companion keyword. Its members are accessed through the class name, serving the role of static members and factory methods.
Kotlin
Since Kotlin has no static keyword, the companion object fills that gap. Declared once per class, it holds constants (const val), factory functions, and any class-level state, all reachable as ClassName.member without an instance.
A frequent pattern is a private constructor plus a companion factory, so callers create instances through a controlled function (User.fromJson(...)) rather than the constructor directly. const val inside it defines true compile-time constants.
Because it's a real object, a companion can implement interfaces, be named, and even be extended with extension functions — capabilities Java statics lack. This makes it more flexible than a plain bag of static methods.
Syntax
class Token {
companion object {
const val PREFIX = "tok_"
fun new() = Token()
}
}Examples
Kotlin
class Counter private constructor(val start: Int) {
companion object {
fun zeroed() = Counter(0)
}
}
println(Counter.zeroed().start)Output:
0