What static members are
Most members of a class belong to each object. Every Dog has its own name. Sometimes you need data that belongs to the class as a whole, shared by all objects, such as a counter of how many objects exist. Many languages call this a static member.
Kotlin has no static keyword. Instead, a class can contain one companion object, and whatever is declared inside it belongs to the class itself. You reach it through the class name: Dog.count, not through an object.
The lesson's task
The editor starts with a Dog class that has only a name, and a Solution class with a mainFunction that you must not change. That function creates Rex and Buddy and prints Dog.count, creates Max, prints the counter and Max's name, creates Luna and prints the counter once more. The program doesn't compile at first, because Dog.count doesn't exist yet. Your job is to create it so that the output is:
2
3
Max
4
The counter starts at 0 before any dog exists and goes up by exactly 1 for every dog created, whatever its name.
Step by step
- Open a companion object. Inside
Dog, writecompanion object { }. Everything inside belongs to the class, not to a single dog. - Declare the shared counter. Inside the companion object, write
var count = 0. It is avarbecause it will change, and it is declared once, so all dogs share the same value. - Open an
initblock. Below the companion object, writeinit { }. Kotlin runs the code in aninitblock each time an object of the class is created. - Count each new dog. Inside
init, writecount++. One object means one run ofinit, which means one increment of the shared counter.
The solution in Kotlin
class Dog(val name: String) {
companion object {
var count = 0
}
init {
count++
}
}
class Solution {
fun mainFunction() {
val rex = Dog("Rex")
val buddy = Dog("Buddy")
println(Dog.count)
val third = Dog("Max")
println(Dog.count)
println(third.name)
Dog("Luna")
println(Dog.count)
}
}
How the output comes about
Before mainFunction runs, count is 0. Creating Rex and Buddy runs init twice, so the first print shows 2. Creating Max makes it 3, which is the second print, and the third print shows Max's name. Dog("Luna") is a statement that creates a dog and drops it, but the object is still created and init still runs, so the last print shows 4.
Kotlin details worth knowing
- Reach it through the class.
Dog.countworks. Writingthird.countdoesn't compile: a companion member isn't reachable through an object, and the compiler reports an unresolved reference. - Inside the class, use the bare name. The
initblock is insideDog, so it writescount++without a prefix. The class's companion is in scope there. - An ordinary property is per object. If
var count = 0were declared directly in the class body, outside the companion, every dog would have its own counter starting at 0, and each would read 1 after its owninit. Two such objects both report 1, not 1 and 2. That is the difference the companion object makes: one value for the whole class, instead of one per object. - A companion can hold functions too. A function declared in the companion, such as
fun describe() = "dogs: $count", is called asDog.describe(). After two dogs are created it returnsdogs: 2. - The shared value can be changed from outside. A public
varin the companion can be assigned: afterDog.count = 10, the next dog makes it 11. In a real program you would usually make the setter private, but the lesson keeps it simple. - There is one companion per class, and it is created when the class is first used, not once per dog. That is why the counter starts at 0 and survives from one dog to the next.
- Order in the class body. The companion object and the
initblock can appear in either order insideDog. The counter exists in either case, because the companion belongs to the class and not to a particular object.
Try it in the editor above: add the four lines one at a time, and the program compiles and prints the expected output once the companion object and the counter both exist.
Common mistakes
- Putting
countin the class body. This gives each dog its own counter, andDog.countdoesn't compile. - Forgetting
init. Without it the counter stays at 0 and every print shows 0. - Counting by name. The counter goes up for every dog, whatever its name, so
initshouldn't testname. - Using
valforcount. Avalcan't be incremented, socount++would not compile. - Editing
mainFunction. The lesson's tests expect those lines as they are. OnlyDogchanges.
Key takeaways
- Kotlin has no
static; acompanion objectholds the members that belong to the class. - Access them through the class name, as in
Dog.count. - An
initblock runs for every new object, which makes it a good place to update a shared counter.
