Problem overview
Many languages let a class hold data that belongs to the class as a whole, not to any single object, using a static keyword. Scala has no static keyword. Class-level members live in a companion object: an object with the same name as the class, declared in the same file. You reach its members through the name, as in Dog.count.
The lesson starts with class Dog(val name: String) and asks you to count how many Dog objects have been created, with one counter shared by all of them. The counter starts at 0 before any dog exists and goes up by exactly 1 per dog, whatever its name. The program already in the editor creates Rex and Buddy and prints the counter, creates Max and prints the counter and Max's name, then creates Luna and prints the counter again. The expected output is:
2
3
Max
4
Approach: one counter in the object, one increment in the class body
Two ideas fit together here.
First, the shared counter belongs in the companion object. An object in Scala is a single instance created once, so a var inside it exists exactly once, no matter how many dogs there are. This is what Java's static fields do.
Second, the code written directly in the body of a class, outside any method, runs every time an object is created. That makes the class body the right place for the increment: each Dog(...) call runs it once.
Step by step
- Below
class Dog, writeobject Dogwith avar count = 0inside. The name must match the class exactly, and it must be in the same file, or the object is not a companion. - Inside the body of
class Dog, writeDog.count += 1. HereDogon the left of the dot means the object, not the class. Every new dog adds 1 to the shared counter.
The solution in Scala
class Dog(val name: String) {
Dog.count += 1
}
object Dog {
var count = 0
}
class Solution {
def mainFunction(): Unit = {
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)
}
}
The class Solution is the program that was already in the editor, and it is unchanged. Walking through it with the finished Dog:
- Creating
RexandBuddyruns the class body twice, so the firstprintln(Dog.count)shows 2. - Creating
Maxmakes it 3. The program then prints the counter, 3, and the name,Max. Dog("Luna")creates a fourth dog even though the result is not stored in a variable. The class body runs anyway, so the last line shows 4.
Scala details that matter
- Creating objects without
new. In Scala 3,Dog("Rex")works the same asnew Dog("Rex")for a class. The class body runs either way. - Reading the counter before any dog exists.
Dog.countis 0, because the object's initializer sets it. After running the whole program above,Dog.countis 4. - The counter is reached through the name, not through a dog. If you write
val d = Dog("Rex")and thend.count, the compiler reportsvalue count is not a member of Dog. The member belongs to the objectDog, so you writeDog.count. - The companion object must exist. If you write
Dog.count += 1in the class but never declareobject Dog, the compiler reportsvalue count is not a member of object Dog. The two declarations go together. - Why not a
varin the class? Avar count = 0insideclass Dogis created again for every dog. Two such objects each start from 0 and each reports 1 after being created, so nothing is shared. A counter that all dogs share must live in the object. - When the object is created. An object is initialized the first time it is used, not when the program starts. A
printlnplaced in an object's body appears only after the program first touches the object, and every use after that sees the same instance. ForDog, the first use is the firstDog.count += 1orDog.countread, and that is also why the counter is already 0 at that moment. - Companions can see each other's members. A class and its companion may use each other's private members, which is one reason the pair is declared together. This lesson only needs a public
var.
Edge cases and common mistakes
- Putting the increment in the wrong place. The increment must be in the class body, not in the object. In the object it would run once, when the object is first used, not once per dog.
- Counting with a different name. Every dog counts, whatever its name, so the increment doesn't depend on
name. - Changing the editor program. The lines that create the dogs and print the counter stay as they are; only
Dogchanges. - Confusing the class and the object. They share a name but are two separate things: the class describes dogs, and the object is a single value that holds the shared state.
