Kotlin
companion object
Learn class-level members with companion object.
Companion object
The companion object defines class-level members. Kotlin has no static keyword; instead, members inside a companion object are accessed through the class name.
Example: class Counter { companion object { var total = 0; fun create() = Counter() } }. You call Counter.total and Counter.create(). Each class can have only one companion object. Members are accessed through the class name, so they are usable without an instance.
Factory method
A method inside a companion object can act as a factory: it centralizes instance creation. It is useful to enforce constraints, keep counters or return different subtypes.
Example: companion object { var total = 0; fun create(): Counter { total += 1; return Counter() } }. Each call to create increments total. The companion object tracks how many instances have been produced. This is a clean way to manage setup logic without leaking it outside the class.
Exercise Add a companion object to the Counter class
Define a class named Counter with a primary constructor taking val id: Int. Add a companion object containing var total: Int = 0 and a fun create(): Counter method. The create method increments total by 1 and returns Counter(total). In main call Counter.create() twice, then print Counter.total and the second instance's id.
Show example solution
class Counter(val id: Int) {
companion object {
var total: Int = 0
fun create(): Counter {
total += 1
return Counter(total)
}
}
}
fun main() {
val a = Counter.create()
val b = Counter.create()
println(Counter.total)
println(b.id)
}
Test yourself
-
Which statement about companion object is correct?
- A class can have multiple companion objects
- Companion object members are called through the class name
- Companion object members are called on an instance
- A companion object can contain only val
Show answer
Companion object members are called through the class name — Companion object members are accessed through the class name.
-
Match the companion object parts
- companion object
- Block keyword
- var total = 0
- Class-level state
- fun create()
- Factory method
- Counter.total
- Class-name access
-
Complete the companion object block
class Counter {
____ object {
var total = 0
}
}
Show answer
class Counter {
companion object {
var total = 0
}
}
Next lesson: Summary - Classes