Start learning free

LESSON 401 OF 414 · OBJECT-ORIENTED PROGRAMMING

Static Members in Scala in Scala

Practice

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

    Static Members in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free