TL;DR:
Kotlin has no static keyword. Class-level members live in a companion object inside the class, and you reach them through the class name: Dog.count. An init block runs 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.
- Inside
Dog, add acompanion objectwithvar count = 0. - Add an
initblock that doescount++, 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) {
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)
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
