Start learning free

LESSON 29 OF 70 · OBJECT-ORIENTED PROGRAMMING

Static Members in Scala: Companion Objects and a Shared Counter

Practice Read the full explanation

TL;DR:

Scala has no static keyword. Class-level members live in a companion object: an object with the same name as the class, declared next to it. You reach them through the name: Dog.count. Statements written in the body of a class run every time an object is created.

You start with:

class Dog(val name: String) {
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Below the class, add object Dog { var count = 0 } (written over several lines).
  • Inside the body of class Dog, add Dog.count += 1, so every new Dog is counted.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog.count.

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)
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · OBJECT-ORIENTED PROGRAMMING

    Static Members in Scala, explained

    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

    1. Below class Dog, write object Dog with a var count = 0 inside. The name must match the class exactly, and it must be in the same file, or the object is not a companion.
    2. Inside the body of class Dog, write Dog.count += 1. Here Dog on 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 Rex and Buddy runs the class body twice, so the first println(Dog.count) shows 2.
    • Creating Max makes 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 as new Dog("Rex") for a class. The class body runs either way.
    • Reading the counter before any dog exists. Dog.count is 0, because the object's initializer sets it. After running the whole program above, Dog.count is 4.
    • The counter is reached through the name, not through a dog. If you write val d = Dog("Rex") and then d.count, the compiler reports value count is not a member of Dog. The member belongs to the object Dog, so you write Dog.count.
    • The companion object must exist. If you write Dog.count += 1 in the class but never declare object Dog, the compiler reports value count is not a member of object Dog. The two declarations go together.
    • Why not a var in the class? A var count = 0 inside class Dog is 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 println placed in an object's body appears only after the program first touches the object, and every use after that sees the same instance. For Dog, the first use is the first Dog.count += 1 or Dog.count read, 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 Dog changes.
    • 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.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free