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, addDog.count += 1, so every newDogis 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
RexandBuddyand prints the counter; then it createsMax, prints the counter and Max's name, createsLuna, 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)
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
